简体   繁体   中英

One event handler negates another in jquery — click()

I am having an issue where when one click() handler is called then the other click() handler on a different element won't be called again.

Basic HTML Elements

<label for="pix_size">Default Pixel Size:</label><br>
<input id="pix_size">
<button id="action">Action</button>
<div id="here_table"></div>

Then there is some jquery code to create a table, add classes to the columns, etc. I didn't include here because I wanted to keep it succinct.

Here are the event handlers that appear to be in conflict

$("tr.remRow").click(function() {    // do something when a specific row was clicked
   alert(($(this).index() + 1) + " row was clicked" + 
         "and its rem value is " + $(this).children(".remColumn").text()); 
});

$("#action").click(function () {    // button event handler
    curPixSize = $("#pix_size").val(); // this refers to the 2nd row in the table
    redrawTable(3,5, curPixSize); // redraw the table with the new value from the input
});

the tr.remRow works great until I click the button, then it will never be called again. I am sure I just don't understand some jquery binding mechanism but a point in the right direction would be great. I want users to be able to click the button, focus/blur the input element, etc and then still be able to click on a row in the table.

try using something like

$('table').on('click', 'tr.remRow', funciton () {
alert(($(this).index() + 1) + " row was clicked" + 
         "and its rem value is " + $(this).children(".remColumn").text());
} 

IF this is your markup:

<label for="pix_size">Default Pixel Size:</label><br>
<input id="pix_size">
<button id="action">Action</button>
<div id="here_table"><table>
rest of table here
</table></div>

and you have code that replaces that table, then this would make it work:

$("#here_table").on('click',"tr.remRow",function() { 
   alert(($(this).index() + 1) + " row was clicked" + 
         "and its rem value is " + $(this).children(".remColumn").text()); 
});
// no change here:
$("#action").click(function () {  
    curPixSize = $("#pix_size").val();
    redrawTable(3,5, curPixSize);
});

add delegate to the first parent element that is not redrawn. in this case, i guess that is here_table element.

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