Pass variables through Quoted Javascript String

243 Views Asked by At

I have a function which returns a string which contains a javascript call. Since it is quoted I cannot pass variables through it.

How can I change the return string which would enable me to pass javascript object values.

Ex: How can I pass var i through the return statement.

var i = 'iaa';

return '<a href="javascript:abccd(\'i\');" ><img src="../images/btnsave2.png" style="margin:6px 0 0 6px;" height="13" width="13" /></a> ';

2

There are 2 best solutions below

2
katspaugh On BEST ANSWER

If you need to manipulate raw HTML, at least add the event handler separately, in JavaScript. And styles in a CSS file.

Your image tag code should contain a data- attribute:

i = i.replace(/"/g, '\\"')
return '<img data-input="' + i + '" src="../images/btnsave2.png" />'

Then adding a listener is as simple as that:

var onClick = function (e) {
    var data = e.target.getAttribute('data-input')
    if (data) {
        abccd(data)
    }
}

/* Firefox, Chrome &c */
if (document.addEventListener) {
    document.addEventListener('click', onClick, false)
/* IE <9 */
} else if (document.attachEvent) {
    document.attachEvent('onclick', function () {
        return onClick({ target: event.srcElement })
    })
}

Of course, XSS problems, mentioned by @Quentin, are still a concern. But at least you won't have to escape nested quotes in the inline handler as in your original example.

3
khael On

Try this, but please reconsider your actions before putting into practice.

var i = "halo";
return '<a href="javascript:abccd(\''+i+'\');" ><img src="../images/btnsave2.png" style="margin:6px 0 0 6px;" height="13" width="13" /></a> ';