开发者

jQuery: I'm trying to bind a click action to multiple elements with the same class

开发者 https://www.devze.com 2023-01-16 16:47 出处:网络
<script type=\"text/javascript\"> $(document).ready(function() { $(\".slider_link\").each(function(i, elem){
<script type="text/javascript">
$(document).ready(function() {
    $(".slider_link").each(function(i, elem){
   开发者_如何学运维     elem.click(function(){
            $("div#"+elem.attr("tag")).slideUp(300);
        });
    });
});

</script>

but after the first one (checked with alert) it breaks saying index.html has no method click... whats up with that?

html:

        <li><a href="#" tag="home" class="slider_link">Home</a></li>
        <li><a href="#" tag="calendar" class="slider_link">Calendar</a></li>
        <li><a href="#" tag="officers" class="slider_link">Officers</a></li>
        <li><a href="#" tag="media" class="slider_link">Media</a></li>


The problem is that elem is the current DOM element, not a jQuery object which has the .click() method, you either to wrap it in a jQuery object using $() like this:

$(document).ready(function() {
    $(".slider_link").each(function(i, elem){
        $(elem).click(function(){
            $("div#"+$(elem).attr("tag")).slideUp(300);
        });
    });
});

Or even shorter just bind all of them the same and get the attribute when any one is clicked:

$(function() {
  $(".slider_link").click(function(){
    $("#"+$(this).attr("tag")).slideUp(300);
  });
});

An even better solution would be to make this simpler and work with JS disabled, change your markup like this:

 <li><a href="#home" class="slider_link">Home</a></li>
 <li><a href="#calendar" class="slider_link">Calendar</a></li>
 <li><a href="#officers" class="slider_link">Officers</a></li>
 <li><a href="#media" class="slider_link">Media</a></li>

Then you can bind your click handler like this:

$(function() {
  $(".slider_link").click(function(e){
    $(this.hash).slideUp(300);
    e.preventDefault(); //prevent page scroll
  });
});

This works even if JS is disabled, it'll just scroll the page to the <div id="home">, etc when you click the corresponding link.

0

精彩评论

暂无评论...
验证码 换一张
取 消