[英]How can I determine the element type of a matched element in jQuery?
我通過ID名稱匹配ASP.Net生成的元素,但是有些元素可能會根據頁面上下文呈現為文本框或標簽。 我需要弄清楚是匹配到文本框還是標簽,以便知道是通過val()還是通過html()獲得內容。
$("[id$=" + endOfIdToMatch + "]").each(function () {
//determine whether $(this) is a textbox or label
//do stuff
});
我發現了一個無效的解決方案,它只會返回“ undefined”:
$("[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真是個不錯的提示。 我還建議使用tagName.toLowerCase(),因為返回的值取決於文檔類型(HTML或XML / XHTML)。
請參閱: 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()
語句中使用值做一些事情
可以說更為優雅的另一種解決方案是為每種元素類型編寫兩個單獨的函數:
$("input#" + id).each(function() { alert(this + " is an input"); });
$("label#" + id).each(function() { alert(this + " is a label"); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.