获取 json 元素的标签及其 id
本文关键字:id 标签 json 元素 获取 | 更新日期: 2023-09-27 18:36:34
我有这种形式的json元素;
<rect style="fill: #888888; display: inline;" id="17" width="35.823246" height="35.823246" x="456.61066" y="65.9505" class="seatObj" label="A18"></rect>
如何获取属性label
值?
假设<rect .../>
标记 xml 的一部分,那么如何使用 C# 控制台应用程序获得相同的内容?
试试这个:
var elem = document.getElementsById('17');
var label = elem.getAttribute('label');
alert(label);
使用 jQuery:
alert($('#17').attr('label'));
你有 300 个这样的元素:
然后试试这个:
$('rect').each(function(){
alert($(this).attr('label'));
});
这是演示
另一种方法是将类属性添加到 rect 元素中,然后使用该类选择它们。我添加了class="sample"
矩形元素。检查这个小提琴
$('.sample').each(function(){
alert($(this).attr('label'));
});
示例 xml 文件。
<?xml version="1.0" encoding="utf-8" ?>
<Test>
<rect style="fill: #888888; display: inline;" id="17" width="35.823246" height="35.823246" x="456.61066" y="65.9505" class="seatObj" label="A18"></rect>
<rect style="fill: #888888; display: inline;" id="18" width="35.823246" height="35.823246" x="456.61066" y="65.9505" class="seatObj" label="A19"></rect>
</Test>
使用 C# 控制台应用程序分析 XML:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace Sample
{
class Program
{
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
doc.Load("Url for Sample.xml");
XmlNodeList elemList = doc.GetElementsByTagName("rect");
for (int i = 0; i < elemList.Count; i++)
{
string attrVal = elemList[i].Attributes["label"].Value;
Console.WriteLine(attrVal);
}
Console.ReadLine();
}
}
}
试试这个:
var elem = $('#' + id)
alert(elem.attr("label"));
首先,label
不是一个有效的 DOM 属性。您需要将其更改为 data-label
.如果要使用任何自定义属性,则需要将它们与前缀一起使用data-
。
此外,id
属性的第一个字符必须是字母,例如 a17
,不是17
。
如果您考虑上述两个,那么要访问此属性,您可以执行
$('#a17').attr('data-label')
或纯JavaScript
document.getElementById('a17').dataSet.label