1

I have a string like this:

  var b = "<button type='button' onclick='javascript:"+f+"(\""+ encodedString+"\");'> hi</button>"
    //encodedString = "a &quot; &lt;hr&gt; &lt;br&gt;"

and after I do something like:

$('li').append(b);

after this the encodedString becomes decoded and my onclick doesn't work because of the &quot becoming "

1 Answer 1

1

Instead of directly setting the click event through html, bind an event listener. eval(f) allows you to refer to functions by a string. If possible, I recommend passing a direct reference to the function.

If the function is defined in the global scope, use window[f]. Note: This won't work if f looks like Math.round, because window["Math.round"] != window["Math"]["round"].

//f is a string which contains a single function name.
var b = $('<button>').click(function(){
   eval(f)(encodedString); 
});
$('li').append(b);

If f is a dynamic variable, which changes (eg, in a loop), wrap the code in an anonymous function:

(function(f){
    var b = $('<button>').click(function(){
       f(encodedString); 
    });
    $('li').append(b);
})(eval(f));
Sign up to request clarification or add additional context in comments.

2 Comments

my function is not known, i have f which is the string function name
@ChuckNorris Try my answer. Function("return "+f) is a method to convert a function name to a function reference. Another method is using eval(f) (instead of Function('return '+f)).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.