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