javascript - How to pass a html object multiple times -


my problem following:

i have onclick function. function have param current element object , status code. whole function should redeclared @ clicking function.

onclick

<button onclick="test(1, this);">test</button> 

function

function test(status, obj) {      if(status == 0)  $(obj).attr('onclick','test(1, '+ obj +')');      else if(status == 1)  $(obj).attr('onclick','test(0, '+ obj +')');   } 

the problem html element after first click not working. error message:

uncaught syntaxerror: unexpected identifier 

note: dummy function. questions general thing.

question: why can not pass parameter obj function 1 more time?

the code example of problem. know there several solutions this. want understand why not working.

it not working this.

no idea why such thing can achieved using plain javscript.

furthermore you're passing actual object (obj) onclick whereas should use "this" because evaluated later.

solution:

function test(status, obj){    alert(status);    if(status == 0){  	  obj.setattribute("onclick", "test(1,this);");  	}  	else if (status == 1){  	  obj.setattribute("onclick", "test(0,this);");  	}  }
<!doctype html>     <html>      <head>          <title>example</title>          <meta charset="utf-8">          <meta name="viewport" content="width=device-width">      </head>      <body>            <div>              <button type="button" onclick="test(1,this);" >click</button>          </div>             </body>  </html>

the same true jquery answer:

function test(status, obj) {    alert(status);    if(status == 0)  $(obj).attr('onclick','test(1, this)');     else if(status == 1)  $(obj).attr('onclick','test(0,this)');    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <!doctype html>     <html>      <head>          <title>example</title>          <meta charset="utf-8">          <meta name="viewport" content="width=device-width">      </head>      <body>          <div>              <button type="button" onclick="test(1,this);" >click</button>          </div>      </body>  </html>


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -