change() for appended select doesn't work

前端 未结 4 897
太阳男子
太阳男子 2021-01-03 11:52

I\'ve jQuery function on change for a select element:

$(\"#category\").change(function(){
    $(\"table[id=advance_search]\").append(\"

        
4条回答
  •  伪装坚强ぢ
    2021-01-03 11:57

    The problem here is because change() (and all other event handler shortcuts) are bound on page load, yet your element is added dynamically well after this. Instead you need to use delegate() to attach the events to this element after it's appended.

    $("tr[id=item_type]").delegate("select[id=type]", "change", function() {
        console.log("change");
    });
    

    Or, if you're using jQuery 1.7+ you can use on():

    $("tr[id=item_type]").on("change", "select[id=type]", function() {
        console.log("change");
    });
    

    You may want to amend the select element you're appending here though, as it has an ID, which could be easily duplicated if it's appended multiple times, which would render the page invalid.

提交回复
热议问题