jQuery에서 태그 이름을 제공할 수 있습니까?
HTML 페이지에 같은 클래스를 가진 여러 요소가 있지만 요소 유형이 다릅니다.요소를 루프할 때 요소의 태그 이름을 확인하고 싶지만 .attr는 "태그" 또는 "태그 이름"을 사용하지 않습니다.
제 말은 이렇습니다.페이지에서 다음과 같은 요소를 고려해 보십시오.
<h1 class="rnd">First</h1>
<h2 id="foo" class="rnd">Second</h2>
<h3 class="rnd">Third</h3>
<h4 id="bar" class="rnd">Fourth</h4>
이제 이와 같은 작업을 실행하여 요소가 이미 정의되지 않은 경우 모두 ID를 가질 수 있도록 하겠습니다.
$(function() {
$(".rnd").each(function(i) {
var id = $(this).attr("id");
if (id === undefined || id.length === 0) {
// this is the line that's giving me problems.
// .attr("tag") returns undefined
$(this).attr("id", "rnd" + $(this).attr("tag") + "_" + i.toString());
}
});
});
제가 원하는 결과는 H2 및 H4 요소가 다음과 같은 ID를 가지는 것입니다.
rndh2_1
rndh4_3
각각 다음과 같다.
'이것'으로 표현되는 요소의 태그 이름을 어떻게 찾을 수 있는지에 대한 아이디어가 있습니까?
이것을 시도해 볼 수 있습니다.
if($(this).is('h1')){
doStuff();
}
is()에 대한 자세한 내용은 문서를 참조하십시오.
$(this).attr("id", "rnd" + $(this).attr("tag") + "_" + i.toString());
그래야 한다
$(this).attr("id", "rnd" + this.nodeName.toLowerCase() + "_" + i.toString());
이전에 이 질문에 한 번 부딪힌 적이 있는데 제 경우에는 도움이 되지 않았기 때문에 (전 그런 질문이 없었습니다.)this, 대신 jQuery selector 인스턴스(jQuery selector instance)가 있었습니다.호출하면 HTML 요소를 얻을 수 있고, 이를 통해 위에서 언급한 것을 얻을 수 있습니다.
this.nodeName; // In a event handler, 'this' is usually the element the event is called on
아니면
$('.hello:first-child').get(0).nodeName; // Use 'get' or simply access the jQuery Object like an array
$('.hello:first-child')[0].nodeName; // will get you the original DOM element object
사용할 수도 있습니다.$(this).prop('tagName');jQuery 1.6 이상을 사용하는 경우.
예. 아래 코드를 사용할 수 있습니다.
this.tagName
제 생각에 당신은 사용할 수 없습니다.nodeNamenodeName이 DOM 속성이고 jQuery 자체에 a가 없으므로 jQuery에서nodeName함수 또는 속성.그러나 이에 관해 처음 언급한 피청구인을 기준으로 할 때,nodeName제가 문제를 해결할 수 있었던 방법은 이렇습니다.
this.attr("id", "rnd" + this.attr("nodeName") + "_" + i.toString());
참고:this여기 jQuery 오브젝트가 있습니다.
jquery tagname first child를 쿼리로 사용하여 Google에 제공되는 질문이므로 다른 예를 게시합니다.
<div><p>Some text, whatever</p></div>
$('div').children(':first-child').get(0).tagName); // ...and not $('div:first-child')[...]
jquery 결과는 (상부) 태그 이름 P입니다.
html 요소 태그 이름을 전체 페이지에서 확인할 수 있습니다.
다음을 사용할 수 있습니다.
$('body').contents().on("click",function () {
var string = this.tagName;
alert(string);
});
you can try:
jQuery(this).get(0).tagName;
or
jQuery(this).get(0).nodeName;
참고: 선택기(h1, h3 또는 ...)로 대체합니다.
다른 문제 때문에 쓴 것일 뿐이고 둘 중 누구에게도 도움이 될 것이라고 생각했습니다.
용도:
- 예.
onclick="_DOM_Trackr(this);"
매개변수:
- 추적할 DOM-객체
- 리턴/리턴 스위치(옵션, default=fault)
소스-코드:
function _DOM_Trackr(_elem,retn=false)
{
var pathTrackr='';
var $self=$(_elem).get(0);
while($self && $self.tagName)
{
var $id=($($self).attr("id"))?('#'+$($self).attr("id")):'';
var $nName=$self.tagName;
pathTrackr=($nName.toLowerCase())+$id+((pathTrackr=='')?'':' > '+(pathTrackr));
$self=$($self).parent().get(0);
}
if (retn)
{
return pathTrackr;
}
else
{
alert(pathTrackr);
}
}
문제를 해결하는 가장 좋은 방법은 대체하는 것입니다.$(this).attr("tag")둘 중 하나로this.nodeName.toLowerCase()아니면this.tagName.toLowerCase().
둘 다 똑같은 결과를 만들어냅니다!
고속 FILTER 방법을 고려합니다.
$('.rnd').filter('h2,h4')
반환:
[<h2 id="foo" class="rnd">Second</h2>, <h4 id="bar" class="rnd">Fourth</h4>]
그래서:
$('.rnd').filter('h2,h4').each(function() { /*...$(this)...*/ });
대신 다음 작업을 수행합니다.
$(function() {
$(".rnd").each(function(i) {
var id = $(this).attr("id");
if (id === undefined || id.length === 0) {
// this is the line that's giving me problems.
// .attr("tag") returns undefined
// change the below line...
$(this).attr("id", "rnd" + this.tagName.toLowerCase() + "_" + i.toString());
});
});
언급URL : https://stackoverflow.com/questions/1532331/can-jquery-provide-the-tag-name
'codememo' 카테고리의 다른 글
| rand() 함수 없이 난수를 생성하려면 어떻게 해야 합니까? (0) | 2023.09.15 |
|---|---|
| setTimeout/clearTimeout 문제 (0) | 2023.09.15 |
| MySQL에서 (flow) 쿼리의 (stock) 결과를 축적하는 방법 (0) | 2023.09.15 |
| 레이아웃을 부풀려서 사용자 정의 보기를 작성하시겠습니까? (0) | 2023.09.15 |
| 도커 컴포지트를 사용하는 PHP MARIADB PHPMYADMIN 문제 (0) | 2023.09.15 |