【问题标题】:jQuery separate function for each clone每个克隆的 jQuery 单独函数
【发布时间】:2014-05-25 19:20:33
【问题描述】:

我在使每个克隆都独立时遇到了问题,目前如果我单击任何克隆,整个“军队”将执行功能 (slideToggle()),而不仅仅是我想要的单个 div。

这是我的 jQuery 脚本

$(document).ready(function(){
    $(".box").click(function(){
        $(".resource").slideToggle();
        });
    $('#clone').click(function(){
        $('div:first').clone().appendTo('body');
    });
});

还有我的身体

<body>
<button id="clone">Add item</button>
<div class="my_inventory">
    <div class="box"> 
    <h2>CLICK HERE</h2>
    </div>

    <div class="resource"> 
    <p>CONTENT HERE</p>
    </div>
</div>
</body>

回顾一下,我希望通过单击相应的&lt;h2&gt; 来单独打开和关闭克隆的每个“框”

我的猜测是我需要在某个地方解决 this 而不仅仅是 jQuery 中的类,但我一直在尝试 $(this).find('.resource') 没有任何成功。

【问题讨论】:

  • 您的代码中缺少某些内容。 id 为“clone”的元素是在哪里创建的?
  • 除了没有id="clone",你真的没有解释到底是什么问题
  • 对不起,只是为了更清楚而编辑了
  • 您要单击h2 来切换.box.resource
  • 切换.resource

标签: javascript jquery


【解决方案1】:

由于绑定事件处理程序时元素(第一个除外)不在 DOM 中,因此您需要将事件处理委托给 在 DOM 中的祖先,在这种情况下,存在的最近的祖先是 body 元素,因此:

// selecting the closest ancestor element to the dynamically-added elements
// that is present in the DOM at the point of event-binding:
$('body')
// using on() to listen for the event(s) (in this case 'click') that occurs on
// the '.box' element(s),
// and then executes the anonymous function:
.on('click', '.box', function () {
    // looks to the parent of the clicked-element:
    $(this).parent()
    // finds the '.resource' element(s):
    .find('.resource')
    // applies the slideToggle() method:
    .slideToggle();
});

JS Fiddle demo.

参考资料:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-07
    • 2011-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多