【问题标题】:Why is jQuery not selecting all attribute elements?为什么 jQuery 不选择所有属性元素?
【发布时间】:2015-05-28 14:15:47
【问题描述】:

我正在网站上制作标签,并设置了 jQuery 以在单击任何属性时运行功能(这只是为了测试选择器,并非所有属性都会在最终网站中使用)。进入某个 div 后,不会选择任何属性。 这是html:

<div id="content" class="content">
     <div id="image" style="border:2px solid;float:left">...</div>
     <div id="backgroundInfo" style="margin-left: 5px;float:left">...</div>
     <br>
     <div id="medBackground" style="margin-left: 5px">...</div>
     <div id="tabs" class="tabs">
         <a> Clowns</a>
         <ul class="tab-links">
              <li class="active"><a href="#tab1">03/05/2001</a></li>
              <li><a href="#tab2">06/05/2007</a></li>
         </ul>
         <div class="tab-content">...</div>
     </div>
</div>

列表是使用 while 循环生成的。除了 div(class= tabs) 中的属性外,所有属性都被选中。 这是 jQuery:

jQuery(document).ready(function() {
    jQuery('a').on('click', function(e)  {
        var currentAttrValue = jQuery(this).attr('href');

        // Show/Hide Tabs
        jQuery('.tabs ' + currentAttrValue).show().siblings().hide();

        // Change/remove current tab to active
                jQuery(this).parent('li').addClass('active').siblings().removeClass('active');

        e.preventDefault();
    });
});

此代码来自:http://inspirationalpixels.com/tutorials/creating-tabs-with-html-css-and-jquery#step-jquery 如果有人可以帮助我弄清楚出了什么问题,那就太棒了。我让它以简化的形式工作,但不在我的主网站上。

【问题讨论】:

  • 您的主要网站上发生了什么?它什么都不做吗?如果您使用 firebug 或 Chrome 开发人员工具单步执行脚本以查看脚本停止的位置(如果停止,否则您可能会遇到选择问题),这可能是最好的选择。
  • 如果您可以编辑上述小提琴以重现您的问题,我们也许可以帮助您
  • 我使用了开发人员工具,但 div(class= tabs) 中的属性没有收到事件。所有其他属性都在开发者工具上附加了一个事件。

标签: jquery html css jquery-selectors attributes


【解决方案1】:

我认为您对动态生成的列表使用了错误的 .on() 方法, 试试

jQuery(document).on('click', 'a', function(e){
    //your code
});

代替

 jQuery('a').on('click', function(e)  {
     //your code
 });

【讨论】:

  • 我试过了,没有选择任何属性。
  • 是的,这行得通!太感谢了!我在想它与动态生成的列表有关。
猜你喜欢
  • 1970-01-01
  • 2012-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-28
  • 2015-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多