我有javascript代码,动态生成并输出一个按钮:
temphtml = temphtml + `
<div class="card border-secondary mb-3" style="max-width: 18rem;">
<div class="card-body">
<h5 class="card-title DataName">` + Name + ` </h5>
<h5 class="card-title DataAge">` + Age + `yrs </h5>
<h5 class="card-title DataGender">` + Gender + `</h5>
<p class="card-text DataHospitalID">Hospital ID:`+ HospitalID + `</p>
<p class="card-text DataMobile">Mobile:`+ Mobile + `</p>
<p class="card-text DataAddress"><small class="text-muted">` + Address + `</p>
<a href="#" id="checkinbtn`+i+`" class="btn btn-primary checkinbtn" data-options='{
Name:"` + Name + `",
Age:"` + Age + `",
Gender:"` + Gender + `",
HospitalID:"` + HospitalID + `",
Mobile:"` + Mobile + `",
Address:"` + Address + `"}'>Check in</a>
</div>
</div> `;
html代码输出如下所示:
<a href="#" id="checkinbtn0" class="btn btn-primary checkinbtn" data-options="{
Name:"First Last",
Age:"28",
Gender:"Female",
HospitalID:"3",
Mobile:"9000000000",
Address:"Somewhere"}">Check in</a>
我正在尝试检索其中一个选项:
$("#checkinbtn0").data( "options" )
给出:
"{
Name:\"First Last\",
Age:\"28\",
Gender:\"Female\",
HospitalID:\"3\",
Mobile:\"9000000000\",
Address:\"Somewhere\"}"
$("#checkinbtn0").data( "options" ).Name
未定义。
逃避特殊字符是一个问题吗?如何检索名称字段之类的值?
答案 0 :(得分:1)
转义特殊字符是否有问题?
有点候。无需像那样逃避,只需按下面的方式编写字符串,然后使用string
将object
转换为$.parseJSON
:
var Name = 'Alex';
var Age, Gender, HospitalID, Mobile, Address;
var temphtml = $('<a href="#" id="checkinbtn0" class="btn btn-primary checkinbtn">Check in</a>').attr({
'data-option': '{"Name": "' + Name + '","Age": "' + Age + '","Gender": "' + Gender + '","HospitalID": "' + HospitalID + '","Mobile": "' + Mobile + '","Address": "' + Address + '" }'
});
$('#target').append(temphtml);
var options = $("#checkinbtn0").attr("data-option");
var obj = $.parseJSON(options);
alert(obj.Name);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="target"></div>
&#13;
请注意,jSON object
名称需要double quotes
。但是,如果您想要符合您的逻辑,那么这是您的原始string
,但已修复double quotes
var Name = 'Alex';
var Age, Gender, HospitalID, Mobile, Address;
var temphtml = `
<a href="#" id="checkinbtn0" class="btn btn-primary checkinbtn" data-options='{
"Name":"` + Name + `",
"Age":"` + Age + `",
"Gender":"` + Gender + `",
"HospitalID":"` + HospitalID + `",
"Mobile":"` + Mobile + `",
"Address":"` + Address + `"}'>Check in</a>`;
$('#target').append(temphtml);
var s = $('#checkinbtn0').data('options');
var str = JSON.stringify(s); // double convert to string
var obj = $.parseJSON(str);
alert(obj.Name);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="target"></div>
&#13;