我的 JS 代码中现在有这个字符串:
newWords = '$(p span.word[style="--' + paraIndex + 'word-index:undefined"], p span.whitespace[style="--' + paraIndex + 'word-index:undefined"])';
我想将此字符串转换为 jQuery 对象,我可以用它来识别这些特定元素。
我还看到了 eval() 函数。这看起来像我想要的那样,但非常不安全/不安全。
有人知道一种安全的方法吗?
最佳答案
最简单的解决方案是删除 $(
和 )
并将剩余的字符串作为参数传递给 $()
:
var paraIndex = 0;
var newWords = '$(p span.word[style="--' + paraIndex
+ 'word-index:undefined"], p span.whitespace[style="--'
+ paraIndex + 'word-index:undefined"])';
var jQ = $(newWords.slice(2, -1));
console.log(jQ);
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
关于javascript - 如何将 jQuery 对象的字符串值转换为实际的 jQuery 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61112708/