简体   繁体   中英

How can I assign click function to many buttons using JQuery?

I have 29 buttons: todayResultsbutton0 .. todayResultsbutton28,
and 29 divs: todayResultsUrls0 .. todayResultsUrls28.
I also have a function toggleVisibility(divName) that hide/show the given div. I am trying to use the following code:

for (var i=0;  i < 29; ++i) {
    var b = "#todayResultsbutton"+i;
    var d = "todayResultsUrls"+i;
    $(b).click(function(){toggleVisibility(d);});
}

I thought that this will cause each button click to show/hide the matching div but the actual result is that clicking on any button (0 .. 28) show/hide the last div - todayResultsUrls28.

Can someone tell me where am I wrong?
Thanks.

Use a class.

$(".myClass").click(function() {
  var d = $(this).attr("id").replace("button", "Urls");
  toggleVisibility(d);
});

Instead of trying to use a loop, you'd be better off using the selector to "find" your divs..

say you have something like:

<table>
<tr><td>
<input type="button" id="myButton" value="test" text="test" />
</td><td><div id="myDiv"></div></td></tr></table>

You can find myDiv by :

$('#myButton').parent().find('#myDiv').hide();

You could use the "startsWith" attribute selector with the id, then build the url from the id of the clicked item.

$('[id^=todayResultsbutton]').click( function() {
     var url = this.id.replace(/button/,'Urls');
     toggleVisibility(url);
});

Use

var d = "#todayResultsUrls"+i;

Instead of

var d = "todayResultsUrls"+i;

Toggle visibility by finding the relevent div usint the event target rather than classes etc.

Assuming:

<div id='todayResultsUrls1'>
    <button id='todayResultsbutton'></button>
</div>

Using the event target you can get the button element and find the div you want to hide.

var parentDiv = $(e.target).parent();
toggleVisibility(parentDiv);

You can use this:

$('button[id^="todayResultsbutton"]').click(function() {
    var index = this.id.substring(18,this.id.length);
    toggleVisibility("todayResultsUrls"+index);
});

This will find all <button> tags with id's starting with todayResultsbutton . It will then get the ID for the clicked tag, remove the todayResultsbutton part of it to get the id and then call the toggleVisibilty() function.

Example here .

Edit
Notes:

  • Using button before the starts with selector ( [id^="todayResultsbutton"] ) speeds up the jQuery selector because it can use the native getElementsByTagName function to get all button tags and then only check those for the specific ID.
  • this.id is used instead of jQuery's $(this).attr('id') because it's faster (doesn't require wrapping this or calling the extra function attr() ) and shouldn't cause any cross-browser issues.

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