我的简单需求是这样的:
我有一个名为loop.php的页面和两个radio A & B,当A被选中时,我加载a.html,当B被选中时,我加载b.html。
loop.php (最重要的部分)
<div>
<input id="radio_one" type="radio" value="radio_one" /> tpl_one
<input id="radio_two" type="radio" value="radio_two" /> tpl_two
<!--template1-->
<div id="tpl_one"></div>
<!-- template 1 end-->
<!-- template2 -->
<div id="tpl_two"></div>
<!--template 2 end-->
</div>a.html
<div>
<input type="button" id="tpl_one_btn" name="" value="in tpl one"/>
</div>b.html
<div>
<input type="button" id="tpl_two_btn" name="" value="in tpl two"/>
</div>我使用的是jquery-1.9,我可以很容易地实现我的需求。所有的jquery代码都在一个名为op.js的文件中
$(function(){
$("#radio_one").click(function(){
$("#tpl_two").hide();
$("#tpl_one").show();
$("#tpl_one").load('a.html');
});
$("#radio_two").click(function(){
$("#tpl_one").hide();
$("#tpl_two").show();
$("#tpl_two").load('b.html');
});
});现在一切都很好,我几乎可以做任何事情,但是当我想要使用a.html和b.html上的按钮时,事情会变得很糟糕。
在op.js中,我想在单击a.html中的按钮时触发事件
$("#tpl_one_btn").click(function(){
console.log('button in a.html');
});没有发生任何事情,这是说我没有通过按钮的id $("#tpl_one_btn")获得按钮我意识到问题可能是因为load方法,所以我做了一个实验,我将按钮移动到loop.php,也就是说,我没有通过jquery ajax函数加载按钮。这一次,上面的代码运行良好。
我的问题是:
1. Why this happed, when I use load method ?
Why I cannot get the button via jquery id selector?
2. If I want to use load method,
how can I got the button using jquery id selector?谢谢大家。
发布于 2013-06-25 22:22:33
您需要使用事件委派(因为您是动态添加按钮)
$(document.body).on('click',"#tpl_one_btn",function(){
console.log('button in a.html');
});https://stackoverflow.com/questions/17299847
复制相似问题