我有一个 JSON 对象,其中包含 jQuery 选择器和值。选择器内的特殊字符(我认为)已被正确转义。 JSON 如下所示:
var config = [{
"fieldname": "First name",
"selector":"\"[id$='txtFirstName']\"",
"value": "Bob"
},
{
"fieldname": "Last name",
"selector": "\"[id$='txtLastName']\"",
"value": "Smith"
}
];
我有代码尝试遍历这些数据,并将相关值应用于选择器指示的控件。该代码如下所示:
$(config).each(
function() {
console.log('selector:')
console.log(this.selector);
var element = $(this.selector);
element.val(this.value);
}
)
当该代码运行时,我得到以下输出:
"selector:"
"\"[id$='txtFirstName']\""
随后出现此错误:
Error: Syntax error, unrecognized expression:
\"[id$='txtFirstName'</a>\""
当选择器被拉出时,双引号似乎再次被编码。为什么会这样呢?我该如何预防呢?
在这里,它解决了您的问题,您错过了“eval”这个词。
$(document).ready(function(){
var config = [{
"fieldname": "First name",
"selector":"\"[id$='txtFirstName']\"",
"value": "Bob"
},
{
"fieldname": "Last name",
"selector": "\"[id$='txtLastName']\"",
"value": "Smith"
}
];
$(config).each(
function() {
console.log('selector:')
console.log(this.selector);
var element = $(eval(this.selector));
element.val(this.value);
}
)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<html>
<body>
First name:
<input type="text" id="txtFirstName" name="txtFirstName" value=""/>
Last name:
<input type="text" id="txtLastName" name="txtLastName" value=""/>
</body>
</html>