jquery以编程方式单击新的dom元素

我试图在jquery中做一些棘手的事情(至少对我来说)。 我有一个绑定到名为add_course的函数的复选框,如下所示:

function add_course(){ var id = $(this).attr('id'); if ($(this).is(':checked')){ if($('#courseInput').val().search(id) < 0){ $('#CourseSummary').append('X '+$('#course'+id+' a').html()+'
'); $('#courseInput').val(function(index,value){ return value+ id +',1;'; }); addTotal($('#price'+id).text()); } imageSync(); }else{ //This is where my question refers to. $('a#'+id+'.courseDel').click(); } }

当有人选中该复选框时,会在页面中添加包含一些数据和链接的范围。 新链接连接到不同的function

 $('.courseDel').live('click', del_course); 

del_course做了很多东西,就像add_course一样。

正如您在add_course函数中看到的那样。 我检查复选框是否已经过检查,只检查过它。

这是del_course:

  function del_course(){ var id = $(this).attr('id'); $('#cn'+id).remove(); $('#courseInput').val(function(index,value){ return value.replace(id+',1;',""); }); subtractTotal($('#price'+id).text()); imageSync(); } 

我想让add_course函数的else部分触发del_course,以便在选中复选框时添加相应的链接。 这不起作用。 我可能过于复杂了。

这是复选框的html(其中一个示例):

  

这是当有人点击复选框时添加的链接的html:

 X Course Title

有人点击链接时效果很好,但我如何以编程方式触发它?

由于您拥有自己创建的元素的ID,因此只需引用ID并使用trigger()方法:

 $('#'+id).trigger('click'); 

此外,只是一个数字的ID不正确:

ID和NAME令牌必须以字母([A-Za-z])开头,后面可以跟任意数量的字母,数字([0-9]),连字符(“ – ”),下划线(“_”) ,冒号(“:”)和句号(“。”)。

使用jquery的trigger()函数。

 $('.courseDel').trigger('click'); 

从长远来看,可能有助于重新组织您的代码,以便您将DOM事件处理与应用程序逻辑分离。

 //Functions to add and remove stuff (these are *not* event handlers) //Since they now receive explicit parameters // you have full power over when to add and remove stuff and functions // can very easily call eachother if needed. //You can have any kind of state you might need, without having to //trick the dom into storing it for you: var currentlySelectedCourse = null; function add_course(id){ //its now easy to access global state like the //currently open course //and it is now easy to call other functions like del_course } function del_course(id){ } //event handling can now become just a simple layer... $('.courseDel').live('click', function(){ var id = //get the id or what parameters you need del_course(id); //pass it to the backend function });