jQuery에서 일치하는 요소의 요소 유형을 어떻게 확인할 수 있습니까?
ASP.Net 생성 요소를 ID 이름으로 일치시키고 있지만 페이지 컨텍스트에 따라 텍스트 상자 또는 레이블로 렌더링 될 수있는 일부 요소가 있습니다. val () 또는 html ()로 내용을 가져올 지 여부를 알기 위해 일치 항목이 텍스트 상자 또는 레이블인지 알아 내야합니다.
$("[id$=" + endOfIdToMatch + "]").each(function () {
//determine whether $(this) is a textbox or label
//do stuff
});
작동하지 않는 솔루션을 찾았으며 "정의되지 않음"만 반환합니다.
$("[id$=" + endOfIdToMatch + "]").each(function () {
alert($(this).tagName);
});
내가 무엇을 놓치고 있습니까?
하나의 jQuery 만 너무 많이 :
$("[id$=" + endOfIdToMatch + "]").each(function () {
alert(this.tagName);
});
each () 를 사용하지 않고이 솔루션을 고려하십시오 .
var elements = $("[id$=" + endOfIdToMatch + "]");
var vals = elements.is("input").val();
var htmls = elements.is("label").html();
var contents = vals.concat(htmls);
다음과 같이 사용할 수도 있습니다.
if ($(this).is('input:checkbox'))
"this"를 필요한 인스턴스로 바꾸고 'checkbox'를 필요한 입력 유형으로 바꾸십시오.
처음으로 내 질문에 답했습니다. 조금 더 실험 한 후 :
$("[id$=" + endOfIdToMatch + "]").each(function () {
alert($(this).attr(tagName));
});
공장!
tagName 좋은 팁입니다. 반환 된 값이 문서 유형 (HTML 또는 XML / XHTML)에 따라 다르기 때문에 tagName.toLowerCase ()도 사용하는 것이 좋습니다.
참조 : http://reference.sitepoint.com/javascript/Element/tagName
jquery 1.6에서는 prop () 사용
예
var el = $('body');
if (el.prop('tagName') === 'BODY') {
console.log('found body')
}
이것은 요소 유형을 얻는 가장 좋은 방법입니다.
function tgetelementType( elmentid )
{
var TypeName = $('#' + elmentid).get(0).tagName;
var TypeName2 = $('#' + elmentid).get(0).type;
if($('#' + elmentid).get(0).tagName== "INPUT")
{
return $('#' + elmentid).get(0).type.toUpperCase()
}
else
{
return $('#' + elmentid).get(0).tagName.toUpperCase() ;
}
}
$("[id$=" + endOfIdToMatch + "]").each(function(){
var $this=jQuery(this),ri='';
switch (this.tagName.toLowerCase()){
case 'label':
ri=$this.html();
break;
case 'input':
if($this.attr('type')==='text'){ri=$this.val();}
break;
default:
break;
}
return ri;
})
문제는 태그 이름을 결정한 후에 무엇을 하시겠습니까? .end ()와 결합 된 추가 선택기를 사용하여 jquery 목록을 쉽게 필터링하여 동일한 작업을 수행 할 수 있습니다.
$("[id$=" + endOfIdToMatch + "]")
.find("input:text")
.each(function(){
/* do something with all input:text elements */
})
.end()
.find("label")
.each(function(){
/* do something with label elements */
})
.end()
위의 예와 같이이 특정 요소 컬렉션으로 추가 작업을 수행해야하는 경우 여전히 연결될 수 있습니다.
두 경우 모두 each()문 내부에서 값으로 무언가를해야합니다 .
Yet another solution, arguably more elegant, is to write two separate functions for each element type:
$("input#" + id).each(function() { alert(this + " is an input"); });
$("label#" + id).each(function() { alert(this + " is a label"); });
'program story' 카테고리의 다른 글
| Math.max.apply ()는 어떻게 작동합니까? (0) | 2020.10.26 |
|---|---|
| Vim에서 두 줄을 어떻게 바꾸나요? (0) | 2020.10.26 |
| COUNT (*)해야합니까? (0) | 2020.10.26 |
| 파이썬에서 -0400 시간대 문자열로 날짜를 구문 분석하는 방법은 무엇입니까? (0) | 2020.10.26 |
| IE에서 CSS 스타일 시트를 동적으로로드 할 수 없습니다. (0) | 2020.10.26 |