Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/462.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 检查元素类名称_Javascript_Jquery_Html_Css Selectors - Fatal编程技术网

Javascript 检查元素类名称

Javascript 检查元素类名称,javascript,jquery,html,css-selectors,Javascript,Jquery,Html,Css Selectors,这应该很快 我需要通过单击两个元素的类名来区分它们。。比如说 html: 或 $this.attrclass,p1实际上设置了class属性。检查$this.attrclass也不好,因为它可能有多个类 或 $this.attrclass,p1实际上设置了class属性。检查$this.attrclass也不好,因为它可能有多个类。如果您想使用$this.attr'class'='p1'{}$this.attr'class',p1'将当前元素的类设置为p1。如果$this.attr'class'

这应该很快

我需要通过单击两个元素的类名来区分它们。。比如说

html:

$this.attrclass,p1实际上设置了class属性。检查$this.attrclass也不好,因为它可能有多个类

$this.attrclass,p1实际上设置了class属性。检查$this.attrclass也不好,因为它可能有多个类。

如果您想使用$this.attr'class'='p1'{}$this.attr'class',p1'将当前元素的类设置为p1。

如果$this.attr'class'='p1'{}是您想要使用的$this.attr'class',p1'将当前元素设置为具有p1类。

$this.hasClass'p1'更快。

$this.hasClass'p1'更快。

用于检查类

$('p').on('click', function() {
    if ($(this).hasClass('p1')) {
        callThisFunction();
    } else {
        doNothing();
    }
});
工作演示:

用于检查课程

$('p').on('click', function() {
    if ($(this).hasClass('p1')) {
        callThisFunction();
    } else {
        doNothing();
    }
});
工作演示:

例如:

例如:

如果您需要区分这样的行为(只有一些元素采取行动),那么您真正应该做的只是绑定到匹配的元素,而不是绑定到每个元素

$('p.p1').on('click', callThisFunction);

这里是goma的JSFIDLE的一个新分支:

如果您需要区分这样的行为(只有一些元素采取行动),那么您真正应该做的只是绑定到匹配的元素,而不是绑定到每个元素

$('p.p1').on('click', callThisFunction);

这里是goma的JSFIDLE的一个新分支:

我正要用hasClass回答,当我看到你的答案改变时,我想知道为什么没有人早点指出它!lolI正要和hasClass一起回答,这时我看到你的答案发生了变化,我想知道为什么没有人提前指出答案!如果.className.match/\bp1\b/,您也可以回退到香草javascript并执行此操作\b是边界空间,等等。如果.className.match/\bp1\b/,您也可以回退到普通javascript并执行此操作\b是边界空间,等等。其他答案完全符合你的要求,但我认为你试图做的需要不同的方法。详见我的答案。其他答案完全符合你的要求,但我认为你要做的需要不同的方法。有关详细信息,请参阅我的答案。
$('p').on('click', function() {
    if ($(this).hasClass('p1')) {
        callThisFunction();
    } else {
        doNothing();
    }
});
$('p').on('click', function() {
    if ($(this).hasClass('p1')) {
        console.log("do something");
    } else {
        console.log("do nothing");
    }
});
$('p.p1').on('click', callThisFunction);