【问题标题】:jquery cannot get button using id selector when use load method使用加载方法时,jquery 无法使用 id 选择器获取按钮
【发布时间】:2013-06-25 14:20:33
【问题描述】:

我的简单需求是这样的:

我有一个名叫loop.php并有两个radio A & B,检查A然后我加载a.htmlB被选中加载b.html

loop.php(最重要的部分)

<div>
    <input id="radio_one" type="radio" value="radio_one" />&nbsp;tpl_one&nbsp;
    <input id="radio_two" type="radio" value="radio_two" />&nbsp;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 的回答,即使您应该使用最接近的静态容器,而不是文档,但两者都可以工作
  • 您可以使用whenthen方法加载页面内容以确保按钮在页面中,然后将事件绑定到按钮。

标签: jquery jquery-load htmlbutton


【解决方案1】:

您需要使用事件委托(当您动态添加按钮时

$(document.body).on('click',"#tpl_one_btn",function(){
    console.log('button in a.html');
});

【讨论】:

  • 谢谢,但是为什么我使用load mehtod的时候会出现这个问题,只是因为它是一个ajax方法并且a.html中的文档没有立即加载?
  • 找到一个有用的链接,谢谢。 stackoverflow.com/questions/9009364/…
  • @diligent 这是因为,当您绑定点击事件(即页面加载时)时,您的按钮不存在,(仅当元素在 DOM 中时才会绑定事件,除非您使用事件委托), , 你可以在我的回答中的链接上找到详细的解释
猜你喜欢
  • 1970-01-01
  • 2011-08-04
  • 2020-02-21
  • 2012-06-14
  • 2021-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
相关资源
最近更新 更多