简体   繁体   English

Javascript DOM:在这种情况下,如何获取元素的类属性值?

[英]Javascript DOM: How can I get the class attribute value of an element in this situation?

As follows, there is an input element on a web page. 如下所示,网页上有一个input元素。

 <input type = "text" class="text-input">

When I click it, the Javascript code will append another class attribute value W_input_focus such as: 当我单击它时,JavaScript代码将附加另一个类属性值W_input_focus例如:

<input type = "text" class="text-input W_input_focus">

Well, how can I get the class attribute value except the value appended by the Javascript when I click on the input? 那么,当我单击输入时,如何获得除Javascript附加的值之外的类属性值? I use getAttribute('class') method to retrieve ,but it return all the values include the js appended. 我使用getAttribute('class')方法进行检索,但它返回的所有值都包括附加的js。

It is an example, actually beforehand I do not know which value is set to class attribute in the html code and which value is appended by js. 这是一个例子,实际上我事先不知道哪个值在html代码中设置为class属性,哪个值由js附加。 And How can I distinguish , Thanks! 我该如何区分,谢谢!

I have found a simple answer: 我找到了一个简单的答案:

$(input).trigger("blur").attr("class")

There's a classList API available for this kind of cases: https://developer.mozilla.org/en-US/docs/Web/API/Element.classList . 对于此类情况,有一个classList API可用: https : //developer.mozilla.org/en-US/docs/Web/API/Element.classList Check the link for examples. 检查链接以获取示例。

It's well supported on browsers except IE (10+): http://caniuse.com/#feat=classlist 除IE(10+)以外的浏览器都很好地支持它: http : //caniuse.com/#feat=classlist

..but there's a polyfill for that: https://github.com/eligrey/classList.js ..但是有一个polyfill: https : //github.com/eligrey/classList.js

To extend this answer: 要扩展此答案:

What you apparently need is Mutation Events / Observers ( https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events ). 您显然需要的是Mutation Events / Observershttps://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events )。 And especially DOMAttrModified , which will dispatch when your className is changed (ie classes are added/removed). 特别是DOMAttrModified ,它将在您的className更改(即,添加/删除类)时调度。

Support is good except on IE(11+) and on Android browsers (4.4+): http://caniuse.com/#feat=mutationobserver 除了在IE(11+)和Android浏览器(4.4+)上以外,支持都很好: http : //caniuse.com/#feat=mutationobserver

...but fortunately on IE, you can use onpropertychange listener: http://msdn.microsoft.com/en-us/library/ie/ms536956(v=vs.85).aspx . ...但是幸运的是,在IE上,您可以使用onpropertychange侦听器: http : //msdn.microsoft.com/zh-cn/library/ie/ms536956( onpropertychange .aspx

An Example (tested on Chrome, FF, IE10) : http://codepen.io/zvona/pen/eGbur/ --> check console for details. 一个示例(在Chrome,FF,IE10上测试)http : //codepen.io/zvona/pen/eGbur/- >检查控制台以了解详细信息。

element.className should provide the class names in string format. element.className应该以字符串格式提供类名称。 You can use String.split(' ') to separate them by spaces (since classes are separated by spaces). 您可以使用String.split(' ')将它们用空格分开(因为用空格隔开)。

Every class you add from js it appends after the class name you already have. 您从js添加的每个类都将追加到您已经拥有的类名之后。 So you can get the classname, split it in " " and get the first element, which is the class name you had in the start. 因此,您可以获取类名,将其拆分为“”,然后获取第一个元素,即开始时使用的类名。

Try 尝试

HTML: HTML:

<input type = "text" class="text-input">

JS: JS:

//ADD SOME CLASSES
$( "input" ).addClass( "W_input_focus" );
$( "input" ).addClass( "class2" );
$( "input" ).addClass( "class3" );

//GET THE CLASS YOU WANT
$( "input" ).click(function() {

    var className = $('input').attr('class');
    var arr = className.split(' ');
    alert(arr[0]);

});

DEMO DEMO

With just JS you can try 只需JS,您就可以尝试

HTML: HTML:

<input id="input" type = "text" class="text-input W_input_focus" onclick="getClass()">

JS: JS:

function getClass(){
  var className = document.getElementById('input').getAttribute('class');
  var arr = className.split(' ');
  alert(arr[0]);
}

DEMO2 DEMO2

JavaScript (no jQuery): JavaScript(无jQuery):

function getClassNames() {
    var element = document.getElementById('spanId');
    var classNames = element.className; //String containing all the classes as they are given in the attribute
    var classes = classNames.split(' '); //Since classes have to be separated by a whitespace, this will return all 'single' classes
}

HTML: HTML:

<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script type="text/javascript" src="classNames.js"></script>
    </head>
    <body> 
        <input type="button" onclick="getClassNames()" value="Get Classnames">
        <span id="spanId" class="class1 class2"></span>
    </body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM