2014-11-21 61 views
0

我試圖寫一些代碼,當點擊一個按鈕時,它們會在後面添加鏈接的href。所以:在jQuery中返回不同的屬性

  • 谷歌
  • 亞馬遜
  • Facebook的

將轉向

  • 谷歌(www.google.com)
  • 亞馬遜(www.amazon.com )
  • Facebook(www.facebook.com)

但是,我的代碼只是放在每個鏈接之後(www.google.com)。我懷疑我打算以某種方式使用$.each(),但無法找到不僅僅返回字符串的在線示例。

我的代碼是:

$(document).on('click', "#button", function(){ 
    $("a").each(function(){ 
     var www = $("a") 
        .attr("href") 
        .replace('http://',' ('); 
     $("a").after(www + ')'); 
    }); 
}); 

我如何修改它來添加正確的鏈接?謝謝。

回答

1

您需要獲取當前元素的屬性。可以通過當前的功能上下文訪問。

var $this = $(this), 
    www = $this.attr("href").replace('http://',' ('); 
$this.after(www + ')'); 

$('#links').click(function(){ 
 
    $('a').each(function() { 
 
    var $this = $(this); 
 
    
 
    $this.after($this.attr('href')); 
 
    }); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button id="links">Links</button> 
 
<a href="http://google.com">Google</a> 
 
<a href="http://foogle.com">foogle</a> 
 
<a href="http://boogle.com">boogle</a>

+0

謝謝 - 我早些時候嘗試過。它只是因爲某種原因在每個鏈接之後添加了所有三個href。 – JohnG 2014-11-21 15:46:19

+0

@JohnG嘗試它的代碼片段。 – 2014-11-21 15:49:33

+0

真棒 - 非常感謝,您的擴展版本只是訣竅。 – JohnG 2014-11-21 15:55:25

0

剛剛獲得當前項目的屬性,當你通過each溫控功能迭代:

$(document).on('click', "#button", function(){ 
    $("a").each(function(){ 
    var $this = $(this); 
    var www = $this.attr("href").replace('http://',' &#40;'); 
    $this.after(www + '&#41;'); 
    }); 
}); 
0

頁面加載後,你會救默認值將用作每次鏈接點擊的基本文本。

$(document).ready(function() { 
 
    
 
    //Save the initial text of the link 
 
    $('ul li a').attr('data-default', function() { 
 
    return $(this).text(); 
 
    }); 
 
    
 
    $('ul li a').on('click', function(e) { 
 
    
 
    //prevent default action 
 
    e.preventDefault() 
 
    
 
    //append the value of href property to initial value and set as test of link 
 
    $(this).text(function() { 
 
     return $(this).data('default') + ' (' + this.href + ') '; 
 
    }); 
 
    
 
    }); 
 
    
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<ul> 
 
    <li><a href="http://www.google.com">Google</a></li> 
 
    <li><a href="http://www.amazon.com">Amazon</a></li> 
 
    <li><a href="http://www.facebook.com">Facebook</a></li> 
 
</ul>

0

首先你需要在同一類添加到鏈接

<a href='www.google.com' class='link' >google</a> 
<a href='www.google2.com' class='link' >google2</a> 
<a href='www.google3.com' class='link' >google3</a> 

其次,你必須創建對象的所有不同的環節

$(document).on('click', "#button", function(){ 
    var links = $('.link'); 
    $.each(links, function(index,value){ 
     var www = value.attr("href").replace('http://',' &#40;'); 
     $(this).after(www + '&#41;'); 
    }); 
}); 

這應該工作,因爲我一直使用它,o最後,我還沒有嘗試過的是.after()