【问题标题】:jQuery - getting the class of a dynamic div by clicking another divjQuery - 通过单击另一个 div 获取动态 div 的类
【发布时间】:2012-04-13 06:31:48
【问题描述】:

正如标题所示,我想通过单击另一个 div(“div.secondclass”)来获取动态 div 的类。这是我的代码:

$(document).ready(function() {
    $("div.secondclass").click(function () {
        firstclass=$('#firstid').attr('class');
        alert("the class of the 1st div is ="+firstclass);
    });
});

【问题讨论】:

  • 这两个 div 是如何相互关联的?
  • 呃,firstid就是id。如果你不知道,你可以用 attr('id') 得到它
  • 有什么问题吗?
  • 究竟是什么不起作用?通过在 firstclass 中执行 firstclass=$('#firstid').attr('class');,您现在应该拥有 div 的类。它应该可以正常工作。确保 div 有一个类集。
  • 只要您知道要查找的第一个元素的 ID,上面的代码应该可以正常工作:jsfiddle.net/steveukx/3PhPC

标签: javascript jquery html


【解决方案1】:
$(document).ready(function() {
    $("div.secondclass").click(function () {
        var aClass = $('#firstid')[0]
                          .className
                          .replace(/[\n\t\r]/g, " ")
                          .replace(/^\s+|\s+$/g, "")
                          .split(" ");
        alert("The div with the id firstid has got these classes: " + aClass.join(", "));
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    • 2012-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多