2016-03-13 38 views
1

我想設置兩個按鈕組。點擊第二組中的任何按鈕應該爲第一組添加一個新按鈕。新按鈕將獲得與點擊按鈕相同的標籤。按鈕組單擊處理程序 - 如何獲取單擊按鈕的文本內容?

var name = this.textContent如果點擊處理程序連接到單個按鈕,則工作。當點擊處理程序被連接到一組按鈕時,如何獲得點擊按鈕的文本內容?

HTML:

<body> 
    <div id="group1"> 
    <button> nameA </button> 
    <button> nameB </button> 
    </div> 
    <hr> 
    <div id="group2"> 
    <button> nameC </button> 
    <button> nameD </button> 
    </div> 
</body> 

的Javascript:

$('#group2').on('click', function(event) { 
    var name = this.textContent // wrong! 
    var r = $('<input type="button" value="' + name + '">'); 
    $("div#group1").append(r); 
}); 

JSFiddle Demo

回答

4

使用事件代表團:

$('#group2').on('click', 'button', function(event) { 
    var name = this.textContent 
    var r = $('<input type="button" value="' + name + '">'); 
    $("div#group1").append(r); 
}); 

'on'方法中的第二個參數可以是選擇器字符串,以篩選觸發事件的選定元素的後代。 檢查這個https://jsfiddle.net/q6b6g3xm/

2

在你的情況,這應該是足夠多:

$('#group2 button').click(function(event) { 
    var name = this.textContent 
    var r = $('<input type="button" value="' + name + '">'); 
    $("div#group1").append(r); 
}); 

比較喜歡RobHil解決方案如果其他按鈕將在執行jQuery代碼後在#group2中創建。

否則,我看其他兩種可能性:

$('#group2 button').each(function() { 
    var $button = $(this).click(function(event) { 
    var r = $('<input type="button" value="' + $button.text() + '">'); 
    $("div#group1").append(r); 
    }); 
}); 

或:

$('#group2').click(function(event) { 
    var $button = $(event.target); 
    var r = $('<input type="button" value="' + $button.text() + '">'); 
    $("div#group1").append(r); 
}); 

但要記住的目標取決於您單擊如果您在點擊區嵌套塊:https://api.jquery.com/event.target/

+0

我寧願第二種方法,並會使用'event.stopPropagation()',以避免任何氣泡:) – user3613129

0

這是我自己的解決問題的方法。我通過在按鈕中添加個人id來修改HTML代碼。

HTML:

<div id="group1" > 
    <button id="btn-A">nameA</button> 
    <button id="btn-B">nameB</button> 
    <button id="btn-C">nameC</button> 
</div> 
    <hr /> 
<div id="group2"> 
    <button id="btn-D">nameD</button> 
    <button id="btn-E">nameE</button> 
    <button id="btn-F">nameF</button> 
</div> 

的JavaScript:

   // click on the button 
      $(document).on('click','button', function(){ 

       //store the value of the id and 
       // split it @ '-' into array ['btn','A'] 
       $id = $(this).attr('id').split('-'); 

       // store the value at index 1 into $id 
       $id = $id[1]; 

       //get the Id of the current div group 
       $divId = $(this).closest('div').attr('id'); 

       //check which div group is current and 
       //Assign the reversed value as appropriate 
       if($divId === "group1"){ 
        $addId = "#group2"; 

       }else { 
        $addId = "#group1"; 
       } 

       //Remove the button from the group 
       $(this).remove(); 

       //Add the button to the second div group 
       $($addId).append('<button id="btn-'+$id+'">'+$(this).text()+'</button>'); 

      });