如何根据属性 ID 获取内部 html

How to get inner html based on attribute Id

本文关键字:获取 内部 html ID 属性 何根      更新时间:2023-09-26

我有属性 Id。

在控制台中,当我输入以下jquery命令时:

$('#LocationRadioButtons a')

我得到以下输出

[<a id=​"4" href=​"#">Test​</a>​, <a id=​"5" href=​"#">Test1​</a>​, <a id=​"6" href=​"#">test2​</a>​]

这是一个数组

如果我输入以下jquery命令:

$('#LocationRadioButtons a').first();

它将返回该数组中的第一个元素:

测试

如何根据元素的 ID 返回元素,并返回其内部 HTML。例如 id = 5 innerHTML 是 test1,

干杯

您可以使用

html()获取html

您可以使用

$('#LocationRadioButtons #5').html();

基于您的标记,您实际上可以简单地使用

$('#5').html();

PS:我不会让 id 以数字开头。HTML4不喜欢这样。

虽然 Id 对于这个元素是唯一的,但你可以直接使用 id 来获取 html

$('#5').html();

试试这个,

$('#LocationRadioButtons a[id$="5"]').text();
id 是唯一的,

因此您可以使用 id 选择器来选择具有特定 id 的元素,如下所示:

 $('#5').html();

试试这个:由于您已经拥有元素 id,只需执行

$('#5').html();

会提醒Test1

当您没有选择器并且想要解析每个元素以检查特定条件时,jQuery each()循环很有用。

$('#LocationRadioButtons a').each(function(index, value){
    var myattr = $(this).attr('id');
    if(myattr=='5') {
        alert( $(this).html() );
    }
});