2013-09-28 85 views
1

好的屬性動態按鈕,我可以生成一個按鈕的形式通過jQuery的

var temp = "<button type=\"button\" class=\"dynBtn\" id=\"anID\">Here!</button>"; 
$('#myDiv').append(temp).click(function(){ 
    window.alert("Hello! My id is " + this.id); 
}); 

的代碼,然後在運行時,這不是真正的工作,因爲我得到的答案爲ID爲「myDiv 」。在另一方面,我還試圖用這樣的:

$('#myDiv').append(temp).click(dynButtonClicked(this)); 

其中dynButtonClicked作爲

function dynButtonClicked (aButton) { 
    window.alert("Hey, my id is " + aButton.id);  
}; 

但是,這樣一來,當加載頁面時點擊按鈕單獨定義的, id是'undefined',而且,無論我點擊多少次按鈕,我都不會收到其他警報(除了我在加載頁面時獲得的警告外)。那麼,我該如何做到這一點?

我想最好我想給一個名稱爲類是在

$(document).ready(...) 

功能點擊任何這些的時候來處理它們在某處運行時生成,然後將所有按鈕的。但請,請繼續並告訴我你的想法。事實上,以後通過交互,我可能想刪除按鈕或禁用它們。所以,我正在尋找強大的東西。預先感謝您的時間。

+0

'click'需要一個功能,你傳遞' undefined'。另外'append'不會給你添加的元素,它仍然是容器。 – elclanrs

+0

我不確定你在暗示什麼是解決方案。 – MightyMouse

回答

5

這裏是如何做到這一點的jQuery的方式:

var $button = $('<button/>', { 
    type: 'button', 
    'class': 'dynBtn', 
    id: 'anID', 
    text: 'Here!', 
    click: function() { 
    window.alert('Hello! My id is '+ this.id); 
    } 
}); 

$button.appendTo('#myDiv'); 
+0

非常感謝您的時間。這與代表團很好地合作。祝你有美好的一天! :) – MightyMouse

+0

其實,這似乎也不完全正確。如果我們將語句更改爲: window.alert('Hello!My class is'+ this.class +'and my id is'+ this.id); 返回的類未定義。建議? – MightyMouse

+0

因爲它是'this.className'。 – elclanrs

1

這是因爲.append()不返回附加的元素,你可以在這種情況下使用.appendTo()

$(temp).appendTo('#myDiv').on('click', function() { 
    window.alert("Hello! My id is " + this.id); 
}); 

如果要添加許多元素的DOM,這將是更好地使用事件委託來代替。

$('#myDiv').on('click', '.appendedElement', fn); 
+0

謝謝。這是行得通的,代表團也在工作。但是,如果我們將警報的參數更改爲: '您好!我的班級是'+ this.class +',我的身份證號碼是'+ this.id 然後班級不打印!你有什麼暗示嗎?當然這似乎很奇怪,因爲之前的jQuery通過委派來選擇基於類的按鈕... – MightyMouse

+0

您是否閱讀了我的評論?它不是'this.class',它是'this.className'。 – elclanrs

+0

@MightyMouse因爲沒有'.class'屬性,所以'.className'。 – undefined

0

上使用(),這樣做:

$(document).ready(function(){ 
    //in here you put the event for all elements with dynBtn class 
    $(document).on("click",".dynBtn",function(){dynButtonClicked();}); 
}); 

function dynButtonClicked (aButton) { 
    window.alert("Hey, my id is " + aButton.id);  
}; 

//and append the button anytime you want 
var temp = "<button type=\"button\" class=\"dynBtn\" id=\"anID\">Here!</button>"; 
$('#myDiv').append(temp); 
+0

我很抱歉,但這甚至沒有生成按鈕。 – MightyMouse