简体   繁体   English

当我向其参数列表提供字符串时,JavaScript事件处理程序功能不起作用

[英]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. 我试图将变量“图像”传递给onclick事件处理函数。 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. 当“ image”变量类似于“ 1111”时,它可以工作,但是当我给它一些字符串值(如“ 11sfrl”)或只是不带数字字符的纯字符串时,则不会调用事件处理函数。 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: 我建议使用jQuery函数,而不要使用一长串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);"> . 这是因为'onclick="deletefromcart(this.id,'+image+');">'变为: onclick="deletefromcart(this.id,IMAGEURL);"> You probably want: 您可能想要:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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