2013-09-24 30 views
0

我想實現一個簡單的jQuery代碼, 一個功能,將新行添加到表:調用jQuery函數使用onclick屬性,將通過「本」的功能

function add_row(){ 
$('#giants_table tr:last').before('<tr><td><input type="text" name="giants_#" id="giants_#"><input type="button" id="removebtn" value="Remove row" onclick="remove_row()"</td></tr>')} 

而第二個函數刪除該行:

function remove_row(){ 
$(this).parents('tr').remove()} 

第一個函數工作得很好,但它似乎在第二個函數中沒有設置「this」選擇器。

任何想法?

+0

刪除包裹'''','this'不是一個字符串,它是一個指針。 – Johan

+0

你有jQuery - 使用它來註冊你的事件處理程序,而不是將它們內聯,並且答案應該變得明顯!更好的是,在整個表上使用一個委託事件處理程序來處理'remove_row'按鈕。 – Alnitak

+0

@Alnitak你怎麼知道他沒有引用jQuery事件處理函數? – Johan

回答

1

您可以使用此兩種方法

  1. this在函數調用來完成。

    function add_row(){ 
        $('#giants_table tr:last').before('<tr><td><input type="text" name="giants_#" id="giants_#"><input type="button" id="removebtn" value="Remove row" onclick="remove_row(this)" /></td></tr>'); 
    } 
    
    function remove_row(ele){ 
        $(ele).parents('tr').remove(); 
    } 
    
  2. 綁定的點擊,並使用$(this)

    function add_row(){ 
        $('#giants_table tr:last').before('<tr><td><input type="text" name="giants_#" id="giants_#"><input type="button" id="removebtn" class="removebtn" value="Remove row" onclick="remove_row(this)"/></td></tr>'); 
        $('#giants_table tr td .removebtn').unbind('click').bind('click', function() { 
          $(this).parents('tr').remove(); 
        }); 
    } 
    

我一定會更喜歡去第二個選項。

1

當您在線註冊事件處理程序(即在HTML代碼中)時,它不會設置this參數 - 它將被設置爲全局(window)對象。

一種選擇是通過this作爲參數remove_row,但你會好得多創建一個一次性的單一委託的事件處理程序,使用jQuery:

$('#giants_table').on('click', 'button', remove_row); 

然後,您可以完全忽略onclick屬性在你的HTML代碼中。由於這是一個「委託」處理程序,它會自動處理添加到表中的每一行,即使事件在註冊時它們不存在。

使用jQuery來註冊你的事件,而不是行內做他們的主要優點是:

  1. this
  2. event對象的保證傳球的自動設置(不同於早期MSIE版本)
  3. 正常化的event對象的屬性來刪除瀏覽器差異
0

You ca n委託click處理程序(可能是更好的解決方案),或者只是在創建行時將其分配。下面的例子(使用DOM元素創建,而不是HTML標記,因爲這是一個更好的做法)。

// delegate the function once in your DOM.ready 
$('#giants_table tr').on('click', 'input[type="button"][value="Remove Row"]', function (e) { 
    $(this).parents('tr').remove(); // this will point to the input 
}); 

// or assign it when you create the row 
function add_row(){ 
    var input = $('<input />'), //create new DOM elements 
     row = $('<tr />'), 
     cell = $('<td />'), 
     rowCount = $('#giants_table tr').length; 
    $('#giants_table tr:last').before(tr.append(td.append(input.clone().attr({ 
     "id": "giants_" + rowCount, 
     "name": "giants_" + rowCount, 
     "type": "text" 
    })).append(input.clone().attr({ 
     "id": "removeRow" + rowCount, 
     "type": "button", 
     "value": "Remove Row" 
    }).click(function (e) { 
     $(this).parents('tr').remove(); // this now points to the input 
    })))); 
} 
+0

當每次調用函數時都重新創建所需元素的新實例時,不需要任何'.clone()'調用。還要注意,MSIE在創建後不允許'input'的'type'屬性被改變。 – Alnitak