我正在使用一个使用querySelectors刮取DOM的Chrome扩展程序。当输入到控制台时,以下querySelector会正确返回我想要的值(全名中的姓氏):
document.querySelector('[data-bind="text:
PersonName.fullName"]').textContent.slice(document.querySelector('[data-
bind="text: PersonName.fullName"]').textContent.indexOf(" ")+1)
但是,在扩展程序中,这些querySelector通过API在JSON对象中提供,并且双引号引起JSON解析错误。是否存在仅使用单引号编写上述查询选择器的等效方法?还是以某种方式转义双引号,以便JSON解析时不会有问题?
如果您想测试一个可能的答案,请尝试以下HTML元素:
<span data-bind="text: PersonName.fullName">John Smith</span>
为了提高清晰度-我无法控制HTML页面,它位于最终用户的计算机上。
这是生成的JSON:
{"AtsMapping":[{"ID":"4"},{"atsCode":"ULT1"},{"atsName":"UltiPro"},
{"atsMapName":"UltiPro"},{"atsMapNotes":"John Smith (1)"},
{"firstName":"document.querySelector('[data-bind="text:
PersonName.fullName"]').textContent.slice(0,document.querySelector('[data-
bind="text: PersonName.fullName"]').textContent.indexOf(" "))"},
{"lastName":"document.querySelector('[data-bind="text:
PersonName.fullName"]').textContent.slice(document.querySelector('[data-
bind="text: PersonName.fullName"]').textContent.indexOf(" ")+1)"},
{"emailAddress":"document.querySelector(".email-address").innerText;"},
{"jobTitle":"document.querySelector('[data-bind="text:
OpportunityTitle"]').textContent"},{"location":""},{"locationDefault":""},
{"effectiveDate":""},{"effectiveDateDefault":""},{"expirationDate":""},
{"expirationDateDefault":""},{"flsaStatus":""},{"flsaStatusDefault":""},
{"compGroup":""},{"compGroupDefault":""},{"benefitsGroup":""},
{"benefitsGroupDefault":""},{"offerTemplate":""},{"offerTemplateDefault":""},
{"confidentialFlag":""},{"confidentialFlagDefault":""}]}
解析此JSON的错误是:
谢谢!
最佳答案
您应该对字符串进行转义。
参见下文,我如何将您的代码转换为字符串并将其添加到json。
当我使用/"/"
时请确保
var d= {"firstName": ""}
var value = "document.querySelector('[data-bind=\"text: PersonName.fullName\"]').textContent.slice(document.querySelector('[data- bind=\"text: PersonName.fullName\"]').textContent.indexOf(' ')+1)";
d.firstName = value;
console.log(d)
关于javascript - 在QuerySelector中仅使用单引号,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54634972/