2015-11-02 75 views
0

我有一样的id多个按钮: #recent_post_button_54#recent_post_button_55如何在多个按钮设置点击事件

当我点击按钮#recent_post_button_54我希望它切换corresponsing #recent_post_content_54格。

我的代码是:

jQuery(document).ready(function($) { 
    var buttons = $('.recent_post_header button'); 
    for (var i = 0; i< buttons.length; i++) { 
    var id = (buttons[i].id).match(/\d+$/)[0]; 

    $("#recent_post_button_"+id).click(function() { 
     console.log("I've clicked #recent_post_button_"+id); 
     $("#recent_post_content_"+id).toggle(); 
    }); 
    } 
}); 

我有IDS 54,52,50三个按钮。但是通过这段代码,我得到了所有按钮的I've clicked #recent_post_button_50,并且所有按钮仅切换与id 50的最后一个内容div。

这段代码有什么问题?

+0

你能提供一个你的HTML样本,你的按钮的父元素 – Anonymous0day

回答

3

使用^(开始于)表达式的id。另外,要获得相应的目标div,请将“post”替换为“content”。

$("input:button[id^='recent_post_button']").click(function() 
{ 
     var id = $(this).attr("id"); 

    var contentID = id.replace("button","content"); 
     $("#" + contentID).toggle(); 

}); 

http://jsfiddle.net/nzyaq8ma/

精缩:

$("input:button[id^='recent_post_button']").click(function() 
{ 
     $("#" + $(this).attr("id").replace("button","content")).toggle();  
}); 
0

尝试这种解决方案using event delegation

jQuery(document).ready(function($) { 
 
    
 
    
 
    $('.recent_post_header').click('button' , function(evt){ 
 
    
 
    var $but = $(evt.target); 
 
    var id = $but.attr('id'); 
 

 
     alert("I've clicked #recent_post_button_" + id); 
 
    
 
    $("#recent_post_content_"+ id).toggle(); 
 
    
 
    }) 
 
    
 
    
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class='recent_post_header'> 
 
    <button id='54'>button 54</button> 
 
    <button id='52'>button 52</button> 
 
    <button id='50'>button 50</button> 
 
</div> 
 
<div id='recent_post_content_52'> 
 
    post 52 
 
</div> 
 

 
<div id='recent_post_content_50'> 
 
    post 50 
 
</div> 
 

 
<div id='recent_post_content_54'> 
 
    post 54 
 
</div>

0

使用所有这些按钮的通用类,如此链接所示(我创建了一个plunker:http://plnkr.co/edit/1xFhmDSo8LUCztDQF9ma)。您可以根据您的要求修改选择器。假设你有这样的按钮,你可以让你的代码如下所示:

<button type="button" id="recent_post_button_54" class="dynamicIdButton">Button1</button> 
<button type="button" id="recent_post_button_52" class="dynamicIdButton">Button1</button> 
<button type="button" id="recent_post_button_50" class="dynamicIdButton">Button1</button> 

<script> 
    $(".dynamicIdButton").click(function() { 
    alert('I have clicked! : ' + this.id); 
}); 
</script>