简体   繁体   中英

JavaScript event handler function not working when i supply string to its parameter list

im trying to pass the variable "image" to the onclick event handler function. When "image" variable is something like "1111" it works, but when i give some string value to it like "11sfrl" or just pure string without numeric characters, the event handler function is not called then. I've tried to wrap it to double quotes on the parameter list but didn't help.

image="ssss";
element4 = $('<div id="elem'+element.id+'" style="position:absolute;width:38px;height:24px;left:123px;margin:2px;border-width:1px;border-style:solid;border-color:red;" onclick="deletefromcart(this.id,'+image+');"></div>').appendTo(element);

I'd suggest doing this with jQuery functions, rather than with a long string of HTML:

element4 = $('<div id="elem' + element.id + '" />')
    .css({
        position: 'absolute',
        width: '38px',
        height: '24px',
        left: '123px',
        margin: '2px',
        borderWidth: '1px',
        borderStyle: 'solid',
        borderColor: 'red'
    })
    .click(function(){
        deletefromcart(this.id, image);
    })
    .appendTo(element);

This will be more reliable than constructing a string.

This is because 'onclick="deletefromcart(this.id,'+image+');">' becomes: onclick="deletefromcart(this.id,IMAGEURL);"> . You probably want:

onclick="deletefromcart(this.id,\''+image+'\');"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM