Javascript 如何将这些信息放入变量中?
如何确保“Good”一词和变量中的数字安全Javascript 如何将这些信息放入变量中?,javascript,jquery,html,css,Javascript,Jquery,Html,Css,如何确保“Good”一词和变量中的数字安全 <div id="infoTable"> <div class='info' label='Good' value='1' minvalue='2' maxvalue='3'></div> <div class='info' label='Bad' value='4' minvalue='5' maxvalue='6'></div> </div> 首先,您可以找到
<div id="infoTable">
<div class='info' label='Good' value='1' minvalue='2' maxvalue='3'></div>
<div class='info' label='Bad' value='4' minvalue='5' maxvalue='6'></div>
</div>
首先,您可以找到
div
,它们位于:
var theDiv = $("#infoTable div").first();
用于查找infoTable
div中的div,然后仅获取第一个div。(您也可以执行var theDiv=$(“#infoTable div:first”);
但它可能没有更高的效率。)
然后读取其属性:
var theLabel = theDiv.attr("label");
var theValue = theDiv.attr("value");
// ...and so on
如果要将数字作为数字而不是字符串,请执行以下操作:
var theValue = parseInt(theDiv.attr("value"), 10);
现在您的
对象中有了所有数据
数组如果您的标记正是您编写的,请使用以下jquery代码:
$(function () {
var $elem = $('#infoTable .info:eq(0)');
var label = $elem.attr('label');
var value = $elem.attr('value');
var minvalue = $elem.attr('minvalue');
var maxvalue = $elem.attr('maxvalue');
})();
使用Javascript
document.getElementById('infoTable').getElementsByTagName('div')[0].getAttribute('label');//Good
document.getElementById('infoTable').getElementsByTagName('div')[1].getAttribute('label');//Bad
你的意思是,你想得到变量中“label”和“value”的值吗?奇数标记。如果需要使用自定义属性,请使用
data-*
attributes@user1803348:不用担心,很高兴这有帮助!顺便说一句,我建议使用将非标准属性放在元素上。
document.getElementById('infoTable').getElementsByTagName('div')[0].getAttribute('label');//Good
document.getElementById('infoTable').getElementsByTagName('div')[1].getAttribute('label');//Bad