Escaping javascript apostrophe / quotation for eval function, so it still works as a selector?

StackOverflow https://stackoverflow.com/questions/23221926

  •  07-07-2023
  •  | 
  •  

Following js code in a jsfiddle:

JS:

function myFunc(foo){
    $(foo).val("magic, it works!... NOT");    
}

var x = "myFunc('input[name=\\'testme\\']')";


eval (x);

HTML:

<input name="testme" type="text" />

Someone got a clue what I could do?

有帮助吗?

解决方案

You need to give this way:

function myFunc(foo){
    $(foo).val("magic, it works!... NOT");    
}

var x = "(myFunc('input[name=\"testme\"]'))";

eval(x);

Combine them inside the (). But you need to also consider this. You need to give in No Wrap (body).

Fiddle: http://jsfiddle.net/praveenscience/243ur/2/

其他提示

Don't use eval.

In your example, you are passing eval a constant string. This can be replaced with simply the contents of the string. That's all eval is actually doing, except using eval makes it impossible for JavaScript engines to optimise your code.

Your example can be replaced with:

function myFunc(foo){
    $(foo).val("magic, it works!... NOT");
}

myFunc('input[name=\'testme\']');
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top