2011-07-28 47 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 
}); 
相关问题