jQuery를 사용하여 요소의 모든 속성 가져 오기
요소를 살펴보고 해당 요소의 모든 속성을 가져 와서 출력하려고합니다. 예를 들어 태그에 3 개 이상의 속성이있을 수 있으며 알 수 없으며 이러한 속성의 이름과 값을 가져와야합니다. 나는 다음과 같이 뭔가를 생각하고 있었다.
$(this).attr().each(function(index, element) {
var name = $(this).name;
var value = $(this).value;
//Do something with name and value...
});
이것이 가능하다면 누구든지 말할 수 있습니까? 그렇다면 올바른 구문은 무엇입니까?
이 attributes
숙소에는 다음이 모두 포함되어 있습니다.
$(this).each(function() {
$.each(this.attributes, function() {
// this.attributes is not a plain object, but an array
// of attribute nodes, which contain both the name and value
if(this.specified) {
console.log(this.name, this.value);
}
});
});
당신이 할 수있는 일은 모든 속성의 일반 객체를 얻는 .attr
것처럼 호출 할 수 있도록 확장 하는 것입니다 .attr()
.
(function(old) {
$.fn.attr = function() {
if(arguments.length === 0) {
if(this.length === 0) {
return null;
}
var obj = {};
$.each(this[0].attributes, function() {
if(this.specified) {
obj[this.name] = this.value;
}
});
return obj;
}
return old.apply(this, arguments);
};
})($.fn.attr);
용법:
var $div = $("<div data-a='1' id='b'>");
$div.attr(); // { "data-a": "1", "id": "b" }
다음은 내 자신의 참조뿐만 아니라 수행 할 수있는 많은 방법에 대한 개요입니다. :) 함수는 속성 이름과 값의 해시를 반환합니다.
바닐라 JS :
function getAttributes ( node ) {
var i,
attributeNodes = node.attributes,
length = attributeNodes.length,
attrs = {};
for ( i = 0; i < length; i++ ) attrs[attributeNodes[i].name] = attributeNodes[i].value;
return attrs;
}
Array.reduce가 포함 된 바닐라 JS
Works for browsers supporting ES 5.1 (2011). Requires IE9+, does not work in IE8.
function getAttributes ( node ) {
var attributeNodeArray = Array.prototype.slice.call( node.attributes );
return attributeNodeArray.reduce( function ( attrs, attribute ) {
attrs[attribute.name] = attribute.value;
return attrs;
}, {} );
}
jQuery
This function expects a jQuery object, not a DOM element.
function getAttributes ( $node ) {
var attrs = {};
$.each( $node[0].attributes, function ( index, attribute ) {
attrs[attribute.name] = attribute.value;
} );
return attrs;
}
Underscore
Also works for lodash.
function getAttributes ( node ) {
return _.reduce( node.attributes, function ( attrs, attribute ) {
attrs[attribute.name] = attribute.value;
return attrs;
}, {} );
}
lodash
Is even more concise than the Underscore version, but only works for lodash, not for Underscore. Requires IE9+, is buggy in IE8. Kudos to @AlJey for that one.
function getAttributes ( node ) {
return _.transform( node.attributes, function ( attrs, attribute ) {
attrs[attribute.name] = attribute.value;
}, {} );
}
Test page
At JS Bin, there is a live test page covering all these functions. The test includes boolean attributes (hidden
) and enumerated attributes (contenteditable=""
).
A debugging script (jquery solution based on the answer above by hashchange)
function getAttributes ( $node ) {
$.each( $node[0].attributes, function ( index, attribute ) {
console.log(attribute.name+':'+attribute.value);
} );
}
getAttributes($(this)); // find out what attributes are available
with LoDash you could simply do this:
_.transform(this.attributes, function (result, item) {
item.specified && (result[item.name] = item.value);
}, {});
Using javascript function it is easier to get all the attributes of an element in NamedArrayFormat.
$("#myTestDiv").click(function(){
var attrs = document.getElementById("myTestDiv").attributes;
$.each(attrs,function(i,elem){
$("#attrs").html( $("#attrs").html()+"<br><b>"+elem.name+"</b>:<i>"+elem.value+"</i>");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="myTestDiv" ekind="div" etype="text" name="stack">
click This
</div>
<div id="attrs">Attributes are <div>
Simple solution by Underscore.js
For example: Get all links text who's parents have class someClass
_.pluck($('.someClass').find('a'), 'text');
My suggestion:
$.fn.attrs = function (fnc) {
var obj = {};
$.each(this[0].attributes, function() {
if(this.name == 'value') return; // Avoid someone (optional)
if(this.specified) obj[this.name] = this.value;
});
return obj;
}
var a = $(el).attrs();
참고URL : https://stackoverflow.com/questions/14645806/get-all-attributes-of-an-element-using-jquery
'Programing' 카테고리의 다른 글
.NET-사전 잠금과 동시 사전 (0) | 2020.07.15 |
---|---|
DomainName을 IP로 변환하는 Linux 명령 (0) | 2020.07.15 |
JSONP를 제공하는 최고의 콘텐츠 유형? (0) | 2020.07.15 |
catch 블록에서 예외를 던지면 마지막으로 언제 실행됩니까? (0) | 2020.07.15 |
Android 애플리케이션의 날짜 / 시간 선택기 (0) | 2020.07.15 |