passing a parameter with onclick function is read as a variable when it should be read as a string

一个人想着一个人 提交于 2019-12-25 08:59:22

问题


Here is my issue:

I am creating dynamically a button with an onclick function like this:

 $("#test).html('<input type="button" value="Close" onclick="remove('+param1+','+param2+');" />');

The parameters are well read but the function is not trigger, and I've got this error message: "bob is not defined" when bob is the string value of the param1.

Apparently it seems that bob is read as a variable when it should be read as a string, but I don't understand why.

Thanks much for your help!


回答1:


That's because this string right here:

'onclick="remove('+param1+','+param2+');"'

Will look like this in the end:

'onclick="remove(foo, bar);"'

You probably want it to look like this:

'onclick="remove(\'foo\', \'bar\');"'

So change it to this:

'onclick="remove(\''+param1+'\', \''+param2+'\');"'

You could also do this:

$("#test").html('<input type="button" value="Close" />').find('input[type=button]').click(function () {
    remove(param1, param2);
});

Edit: I also noticed that you were missing one " from your $()-call: $("#test) should be $("#test").




回答2:


I can suggest you this

<script type="text/javascript">
//<![CDATA[
    var i = 0;
    $(function () {
        $("#lnkAdder").click(function () {
            // appending new item
            $("#Container").append(
                $("<a>").attr({ "href": "javascript:;" }).text("Click me").click(function () {
                    var data = ++i;
                    alert("I'm clicked,  I'm number " + data);
                })
            );
        });
    });
//]]>
</script>
<a href="javascript:;" id="lnkAdder">Add item</a>
<div id="Container"></div>

The key here is the javascript closure. As you can see there a link called lnkAdder. It is responsible to add anew item into the container. On click it appends a new item into the container. While appending you use jQuery API and create a new element, add attributes and add event listener. In the event listener body you copy the value into an internal variable. They use it as appropriate.



来源:https://stackoverflow.com/questions/8940182/passing-a-parameter-with-onclick-function-is-read-as-a-variable-when-it-should-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!