2013-07-19 23 views
0

我試圖在按下按鈕後將複選框添加到項目列表(鏈接)。

的想法是,我得到的鏈接,如清單:

  • Google.com。
  • Bing.com
  • Cnn.com

等,我在頁面底部有按鈕,一旦按鈕被點擊我要添加複選框各個環節,但每箱ID應是它所連接的鏈接的序列號。

$("#links_remove").click(function(event) { 


$('.links').after('<div><label> Check box to remove link: <input type="checkbox" class=" removebox" id="'+$(this).attr("id").split("_")[1]+'"></div>'); 
}); 

這是HTML

<a class="links" id="link_27" href="google.com">google.com</a> 

但當然$(本)選擇獲得按鈕(「links_remove」)的當前連接的屬性,而不是。

謝謝!

+0

當然'this'指的是按鈕,因爲這是分派事件的元素。 –

回答

3

您可以使用函數參數爲after()其中this將指向當前鏈接。

$("#links_remove").click(function(event) { 
    $('.links').after(function(index) { 

     // here "this" refers to the current ".link" and not "#links_remove" 

     return '<div><label> Check box to remove link: <input type="checkbox" class=" removebox" id="'+this.id.split("_")[1]+'"></div>'; 
    }); 
}); 
+1

'$(this).attr(「id」)'可以安全地用'this.id'代替。 – Blender

+0

@Blender - 事實上'this.id'更快更乾淨。 – techfoobar

+0

是的,我跳過避免使用函數,但它實際上很簡單。謝謝! – shultz

0

這應該完成這項工作:

$('.links').each(function(){ 
    $(this).after('<div><label> Check box to remove link: <input type="checkbox" class=" removebox" id="'+$(this).attr("id").split("_")[1]+'"></div>'); 
}); 
0

我只是用一個for-each循環來獲取所有鏈接:http://jsfiddle.net/ehV9L/

$("#links_remove").click(function (event) { 
    $('.links').each(function() { 
     $(this).after('<span><label> Check box to remove link: <input type="checkbox" class="removebox" id="' + $(this).attr("id").split("_")[1] + '"></span>'); 
    }); 
}); 
<ul> 
    <li><a class="links" id="link_01" href="http://www.google.com">Google</a></li> 
    <li><a class="links" id="link_02" href="http://www.bing.com">Bing</a></li> 
    <li><a class="links" id="link_03" href="http://www.cnn.com">CNN</a></li> 
</ul> 
<input type="button" id="links_remove" value="Remove Links" /> 
相關問題