如何使用JavaScript更改onclick? [英] How to change onclick using javascript?

查看:68
本文介绍了如何使用JavaScript更改onclick?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用javascript更改onclick?

How to change onclick using javascript ?

https://jsfiddle.net/749rt0m7/1/

我尝试使用此代码,但不起作用.我该怎么办?

I tried to use this code, but not work. How can i do ?

    <span  onclick="test_fn('aaa,bbb')" id="xx">edit</span>
    <script>
        document.getElementById('xx').onclick = "test_fn(111,222)";
    </script>

推荐答案

这里发生了几件事.

首先,test_fn()不是您的jsfiddle中的函数.您需要定义它才能调用它.

First of all test_fn() is not a function in your jsfiddle. You will need to define it in order for it to be called.

第二个是将onclick属性设置为字符串而不是函数.您必须使用下面的代码将其设置为函数.

Second of all you are setting the onclick attribute to be a string not a function. You would have to set it to be a function using the code below.

document.getElementById('xx').onclick = function() { test_fn(111,222) };

以下是工作jsfiddle的示例.

更新

看来我误解了这个问题.如果您实际上想要更改onclick属性(例如,更改HTML所显示的内容),则需要使用setAttribute().这样您的代码就可以了.

It looks like I misunderstood the question. If you would actually like to change the onclick attribute, as in, change what the HTML shows, you will want to use setAttribute(). So your code would be..

document.getElementById('xx').setAttribute( "onClick", "test_fn('111,222')" );

这是更新的jsfiddle

作为旁注,就像nnnnnn在原始帖子的注释中所说,使用此方法,您似乎通过字符串111,222的函数传递了1个参数,而您似乎想传递两个参数.如果您希望将111作为第一个参数传递,并将222作为第二个参数传递,则可以使用test_fn(111,222)(将参数作为整数传递)或使用test_fn('111','222')(将参数作为字符串传递)来调用该函数. )

As a side note, like nnnnnn says in a comment of the original post, using this you are passing 1 parameter through the function which is the string 111,222 when it seems that you might want to be passing two. If you would like to pass 111 as the first parameter and 222 as the second parameter, you would call the function with either test_fn(111,222) (passing the parameters as integers) or with test_fn('111','222') (passing the parameters as strings)

这篇关于如何使用JavaScript更改onclick?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆