jquery programmatically click on new dom element

前端 未结 3 1066
滥情空心
滥情空心 2020-12-11 02:14

I am trying to do something tricky (at least to me) in jquery. I have a checkbox that is bound to a function called add_course which looks like this:

    fu         


        
相关标签:
3条回答
  • 2020-12-11 02:40

    Since you have the ID of the element that you created, simply refernce the ID and use the trigger() method:

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

    Also, an ID that is just a number is incorrect:

    ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

    0 讨论(0)
  • 2020-12-11 02:42

    Use jquery's trigger() function.

    $('.courseDel').trigger('click');
    
    0 讨论(0)
  • 2020-12-11 02:42

    In the long term, it might help to reorganize your code a bit so that you decouple the DOM event-handling from the application logic.

    //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
    }); 
    
    0 讨论(0)
提交回复
热议问题