繁体   English   中英

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

[英]jquery programmatically click on new dom element

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

    function add_course(){
        var id = $(this).attr('id');
        if ($(this).is(':checked')){

            if($('#courseInput').val().search(id) < 0){
                $('#CourseSummary').append('<span id="cn'+id+'"><a href="#" class="courseDel" id="'+id+'">X</a> '+$('#course'+id+' a').html()+'<br/></span>');
                $('#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();
        }
    }

当某人选中该复选框时,带有一些数据的跨度和链接将添加到页面。 新链接通过以下方式连接到其他功能

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

就像add_course一样,del_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(其中一个示例):

<input type="checkbox" class="courseAdd" name="courseAdd" id="204"/>

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

<span id="cn204"><a href="#" class="courseDel" id="204">X</a> Course Title<br/></span>

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

由于您具有创建的元素的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
}); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM