【发布时间】:2013-06-25 14:20:33
【问题描述】:
我的简单需求是这样的:
我有一个名叫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?
谢谢大家。
【问题讨论】:
-
每周询问一百次...顺便说一句,ID 在上下文页面上应该是唯一的,希望是您的情况
-
@roasted 谢谢,ID 是唯一的
-
还有一百个重复 :(
-
所以,请参阅@pXL 的回答,即使您应该使用最接近的静态容器,而不是文档,但两者都可以工作
-
您可以使用
when和then方法加载页面内容以确保按钮在页面中,然后将事件绑定到按钮。
标签: jquery jquery-load htmlbutton