我在HTML页面上有几个具有相同类的元素 - 但它们是不同的元素类型.我想在循环它们时找出元素的标记名称 - 但.attr不带"tag"或"tagname".
这就是我的意思.在页面上考虑以下元素:
<h1 class="rnd">First</h1>
<h2 id="foo" class="rnd">Second</h2>
<h3 class="rnd">Third</h3>
<h4 id="bar" class="rnd">Fourth</h4>
Run Code Online (Sandbox Code Playgroud)
现在我想运行这样的东西,以确保我的元素都有一个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());
}
});
});
Run Code Online (Sandbox Code Playgroud)
我想要的结果是H2和H4元素的id值为
rndh2_1
rndh4_3
Run Code Online (Sandbox Code Playgroud)
分别.
关于如何发现"this"所代表的元素的标签名称的任何想法?
我通过ID名称匹配ASP.Net生成的元素,但是我有一些元素可以呈现为文本框或标签,具体取决于页面上下文.我需要弄清楚匹配是否是文本框或标签,以便知道是通过val()还是通过html()获取内容.
$("[id$=" + endOfIdToMatch + "]").each(function () {
//determine whether $(this) is a textbox or label
//do stuff
});
Run Code Online (Sandbox Code Playgroud)
我找到了一个不起作用的解决方案,只返回"undefined":
$("[id$=" + endOfIdToMatch + "]").each(function () {
alert($(this).tagName);
});
Run Code Online (Sandbox Code Playgroud)
我错过了什么?