简体   繁体   中英

Unusual behaviour resulting from JQuery bind( )

I am attaching an event to a dynamically created anchor tag using jQuery however I'm getting an unusual effect which I will explain now.

Firstly, this is my jquery

$('#compresult').bind('click', 'a.con_add', function(e){
            console.log(e);
            $companyName = $('#comp_staff option:selected').text();
            $companyId = $('#comp_staff option:selected').val();
            $type = 'company';
            //Display Name of the Company
            $('#item_name').html(" - " + $companyName);
            //Update Hidden Fields of Form
            $('#comp_name').val($companyName);
            $('#comp_id').val($companyId);
            $('#type').val('contact');
            //Make AJAX request to PHP file which will generate the Tags for the Object
            $('#active_tags').load('pages/ajax/get_tags.php', {'name': $companyName, 'id': $companyId, 'type': $type},function(response, status, xhr){});
        });

a.con_add is the class of an anchor tag that does not exist when the page first loads, this is the html for that tag:

 <select style="width:300px" name="comp_staff" id="comp_staff">
           <option value="0">Select Contact...</option>
           <option value="25280">Person1</option>
           <option value="25274">Person2</option>
           <option value="162961">Person3</option>
           <option value="25275">Person4</option>
           <option value="139848">Person5</option>
           <option value="25279">Person6</option>
    </select>
    <a href="#" class="con_add">Add Tag</a>

The strange behaviour is that the click event is triggered when I change the value of this select menu as opposed to clicking on the anchor tag. My guess is that the event is being bind to the entire div that the select menu is contained within?

Any help is much appreciated.

You're using .bind() , but that does, as you theorized, bind the click event to the entire container. Just change that .bind to .on and your event delegation should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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