2011-07-28 31 views
1

,比如我有這樣的代碼:如何onclick事件與jQuery添加到動態A HREF

$("#total").html("Price $<span>" + value + "</span>"); 

,我也想添加一個HREF按鈕有

$("#total").html("Price $<span>" + value + "</span><a id='remove' href='#'>remove</>); 

但我怎麼可能會增加onclick事件爲一個href?

UPDATE

我真的很喜歡這種解決辦法:

//Create the link to remove the item beforehand, and add the onclick event handler. 
var removeLink = $("<a id='remove' href='#'>remove</a>").click(function(e) { 
    //Click event handler here. 
}); 

$("#total").html("Price $<span>" + value + "</span>"); //Create the price value 
$("#total").append(removeLink); //Add the remove link. 

因爲有很多刪除鏈接將是我的形式,但我有一個問題,如何將任何參數傳遞給在這種情況下點擊功能?

回答

3

嘗試這樣的一套分配或鏈接等其他方式:

//Create the link to remove the item beforehand, and add the onclick event handler. 
var removeLink = $("<a id='remove' href='#'>remove</a>").click(function(e) { 
    //Click event handler here. 
}); 

$("#total").html("Price $<span>" + value + "</span>"); //Create the price value 
$("#total").append(removeLink); //Add the remove link. 

它比一個襯墊更詳細一點,但它是在我看來很可讀。


在回答下面的評論,如果你想傳遞參數,你可以在許多方面做到這一點。由於您使用jQuery,還有我能想到的把我的頭頂部的兩個主要途徑:

方法1:匿名函數能夠訪問外部範圍的變量以愛維穩特

var param = 1234;    // <-- We know this value before we create the link 
var removeLink = $("<a id='remove' href='#'>remove</a>").click(function(e) { 
    var someVariable = param + 4321; 
    alert(someVariable);  //Shows "5555" in a message box when link is clicked. 
}); 

方法2:使用jQuery.data

var param = 1234;    // <-- We know this value before we create the link 
var removeLink = $("<a id='remove' href='#'>remove</a>").click(function(e) { 
    var someVariable = jQuery.data(this, 'param') + 4321; 
    alert(someVariable);  //Shows "5555" in a message box when link is clicked. 
}); 
jQuery.data(removeLink, 'param', param); // <-- Save the param as a Jquery data value 
+0

任何想法如何將param傳遞給該點擊函數? – Joper

+0

@Joper - 我已經更新了我的答案,給出了兩個如何將param傳遞給click函數的示例。有幾種不同的方式可以做到這一點,但在使用Jquery時,這是兩種最常見的方式。 –

0

您應該能夠通過使用簡單的jQuery做這個找到功能和點擊處理程序:

var h = $("#total").html("<span>Price $<span>" + value + "</span><a id='remove' href='#'>remove<a/></span>"); 
h.find('a').click(function() { alert('hello') }); 
1

你可以做這幾個方法,live()就是一個例子,或..

$("#total").html("Price $<span>" + value + "</span><a id='remove' href='#'>remove</a>"); 
$("#remove").click(function() { /* ... */ }); 

$("#total").html("Price $<span>" + value + "</span><a id='remove' onclick='doSomething();' href='#'>remove</a>"); 

除了使用

1
$("#total").html(
    $("Price $<span>" + value + "</span>").append(
     $("<a id='remove' href='#'>remove</a>").click(function(){ 
      // Click Handler 
     }) 
    ) 
); 
0

你可以試試這個全光照g鏈接

$("#total").html("Price $<span>" + value + "</span><a id='remove' href='#'>remove</>).find(">a").click(function(){ 
    //on click code goes here 
});