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

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

  •  07-07-2023
  •  | 
  •  

Pregunta

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?

¿Fue útil?

Solución

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/

Otros consejos

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\']');
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top