当我执行“检查元素”时,我得到的HTML代码是
<domain-picker class="pull-right"
current="{"label":"AMN/GRP","value":"assf2324234"}" in-header="true" show-in-header="true">
</domain-picker>
有没有人可以在jquery中告诉我
答案 0 :(得分:6)
以下评论显示步骤
// target element
var $picker = $('domain-picker'),
// parse current attribute value string to object
current= JSON.parse( $picker.attr('current'));
// change value
current.value ='someOtherString';
// stringify object and put back as attribute value
$picker.attr('current', JSON.stringify(current));
答案 1 :(得分:3)
修改HTML,使用当前属性的单引号
<domain-picker class="pull-right"
current='{"label":"AMN/GRP","value":"assf2324234"}' in-header="true" show-in-header="true">
</domain-picker>
var json = $("domain-picker").attr("current");
json = JSON.parse(json)
var value = json.value;
答案 2 :(得分:0)
你需要首先在jquery中获取属性.attr()的值,或者在javascript中获取getAttribute()将有所帮助。现在由于该值是无效的JSON(根据您提供的html),将无效的JSON转换为有效,然后选择该值。
var obj = document.querySelector("domain-picker").getAttribute("current");
var json = obj.replace((/'/g), "\"");
var obj = JSON.parse(json)
//console log the retrieved value.
console.log("value :", obj["value"])
// set attribute now
obj["value"] = "1234567";
document.querySelector("domain-picker").setAttribute('current', JSON.stringify(obj));
<domain-picker class="pull-right"
current="{'label':'AMN/GRP','value':'assf2324234'}" in-header="true" show-in-header="true">
Hello inpsect me to see the changed attribute value.
</domain-picker>
答案 3 :(得分:0)
正如@charlietfl所提到的,如果你想使用jQuery,他的答案是你需要的1,这也可以用纯Javascript来完成,即。
// getting the element
var picker = document.getElementsByTagName('domain-picker')[0];
// parsing current attribute string to object
var current= JSON.parse(picker.getAttribute('current'));
// changing the value
current.value ='newString';
// stringify the object and set the attribute again like
picker.setAttribute('current', JSON.stringify(current));