我有一个属性,我有条件。我从标签的属性中获取了该条件,现在我想将该条件放在 if 块中并获得结果。
我的代码:-
<div myCondition="1 == 2" id="hey"></a>
<script>
var a = document.getElementById('hey');
var x = a.getAttribute('myCondition');
if(x){
console.log('accepted')
}else{
console.log('not accepted')
}
</script>
以上程序应返回不接受myCondition 属性的值可能非常复杂,例如:-
'hello' == 'hello'
5>1 etc
我想你需要的是 eval 函数。正如它在提供的链接中所说:
eval()
函数计算表示为字符串的 JavaScript 代码。
因此,您可以像这样更改代码:
if( eval(x) ){
console.log('accepted')
}else{
console.log('not accepted')
}
PS:话虽如此,我认为这样做并不安全。