【问题标题】:Jquery each inside onclick eventjquery每个里面的onclick事件
【发布时间】:2017-05-10 13:56:56
【问题描述】:

Razor/HTML(其中很多):

<div class="directory-item" id="@item_id" name="@item_name" style="padding-left: @(indent_level)px;  display: @(display)">
   <i class="fa @icon_type"></i>
   @item.ItemName (id: @item_id, name: @item_name, level: @item.Level)
   <i class="fa  fa-angle-right float-right"></i>
</div>

Javascript:

$(".directory-item").click(function () {
    $('div[name*=' + this.id + ']').each(function () {
        if (this.attr('display') == "none") {
            this.show();
        } else {
            this.hide();
        }
    });
});

基本问题:如何将“each”放入“click”事件中并用“this”引用“each”项(每次访问元素时)?也许我不应该使用 each 语句,而是使用其他语句?

【问题讨论】:

  • 是的。您应该使用this 甚至是$(this) 的jQuery 包装项目来访问单击的项目。然后您可以使用closest()find 等方法访问相关项目
  • 你会如何使用 find 重写上面的代码?基本上,我试图获取被点击的 div 的 id,并找到名称包含该 id 的所有 div,然后显示/隐藏切换它们。
  • 您不应拥有多个具有相同 Id 值的项目!那是无效的html。你想达到什么目的?
  • 我没有,再看一遍...我有一个来自项目点击的 id,然后我使用该同上词来查找包含相同名称而不是 id 的所有项目。
  • 我明白了。 this.id 会给你点击项目的ID。

标签: jquery razor click each


【解决方案1】:

在每个方法的回调中,可以有2个参数,一个用于索引,第二个用于循环当前迭代的项目。

$(function () {

    $(".directory-item").click(function () {

        $('div[name*=' + this.id + ']').each(function (a,b) {
            if ($(b).attr('display') == "none") {
                $(b).show();
            } else {
                $(b).hide();
            }
        });
    });
});

如果只是更新可见性,你也可以使用toggle

$('div[name*=' + this.id + ']').each(function (a,b) {
    $(b).toggle();
});

【讨论】:

    【解决方案2】:

    假设有些元素的名称与点击的元素的 id 匹配,您应该可以将其简化为:

    $(".directory-item").click(function () {
            $('div[name*=' + this.id + ']').toggle()
    });
    

    使用toggle() 将在隐藏时显示此类元素,如果未隐藏则将其隐藏,并且不需要each,因为它会在内部循环所有匹配的元素

    【讨论】:

      猜你喜欢
      • 2012-10-06
      • 2013-03-12
      • 1970-01-01
      • 2014-02-18
      • 2018-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多