How to change onclick using javascript?

可紊 提交于 2020-12-08 07:14:09

问题


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>

回答1:


There are a couple things going on here.

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.

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) };

Here is an example of a working jsfiddle.

UPDATE

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')" );

Here is the updated jsfiddle

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)




回答2:


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

When setting onclick in HTML, use a string. When setting it through JS, use a function.




回答3:


You need to set onclick to a function, that runs your code test_fn('111,222'):

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



回答4:


I don't see where you are defining the function test_fn you are hooking the function to the element onclick twice in the html and in js .. only one is needed , and you need to actually define the function

 <span id="xx">edit</span>
 <!-- or .. not both , they are doing pretty much the same thing--> 
 <script>
   document.getElementById('xx').onclick = function(){
     console.log('clicked')
   }
 </script>

now you need to define test_fn it will get called upon clicking the element

function test_fn(arg1 , arg2){
  condole.log(arg1 , arg2)
}

note that the html onclick version is passing one argument and the js script version is passing two argumens.



来源:https://stackoverflow.com/questions/42824309/how-to-change-onclick-using-javascript

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