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