最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Passing multiple onClick parameters using div.innerHTML - Stack Overflow

programmeradmin4浏览0评论

I want to pass multiple parameters to a function that is called via onClick. Here is the code:

 div.innerHTML += '<input type="button" name="back" id="back" value="Back" onClick="homeForm(\'' + form,divName + '\')" />';

function homeForm(form,divName){
//do something   

}

This works with one parameter but not two:

 div.innerHTML += '<input type="button" name="back" id="back" value="Back" onClick="homeForm(\'' + form + '\')" />';

Could someone post a working method for this, or perhaps a cleaner way?

I want to pass multiple parameters to a function that is called via onClick. Here is the code:

 div.innerHTML += '<input type="button" name="back" id="back" value="Back" onClick="homeForm(\'' + form,divName + '\')" />';

function homeForm(form,divName){
//do something   

}

This works with one parameter but not two:

 div.innerHTML += '<input type="button" name="back" id="back" value="Back" onClick="homeForm(\'' + form + '\')" />';

Could someone post a working method for this, or perhaps a cleaner way?

Share Improve this question edited Mar 29, 2016 at 12:44 CommunityBot 11 silver badge asked Sep 9, 2014 at 4:41 shumway21shumway21 793 silver badges11 bronze badges 2
  • Try 'onClick="homeForm(\'' + form,divName + '\')"' in the console and see what happens. Then work from there. If you want to learn how to properly bind event handlers, have a look at quirksmode/js/introevents.html – Felix Kling Commented Sep 9, 2014 at 4:46
  • Thanks Felix. That site looks pretty informative. I will check it out. – shumway21 Commented Sep 9, 2014 at 5:48
Add a ment  | 

4 Answers 4

Reset to default 4

So in the end this code was the only one that worked for me. I'm posting it here in case someone else needs it:

 div.innerHTML += '<input type="button" name="back" id="back" value="Back"    onClick="homeForm(\''+myForm+'\',\''+divName+'\')" />';

Try below, Don't escape it. Concatenate params properly. like below:

div.innerHTML += '<input type="button" name="back" id="back" value="Back" onClick="homeForm(' + form  + ',' + divName + ')" />';

If you’re trying to pass data from a element to an onclick function, a straightforward approach is to pass the IDs of both elements. Then, within the function, retrieve the values associated with those IDs. This makes it easier to handle and evaluate the data.

div.innerHTML += '<input type="button" name="back" id="back" value="Back" onClick=\'homeForm("formId","divId")\' />';

function homeForm(formId,divId)
{
       console.log($("#"+formId));
       console.log($("#"+divId));
}

Easy! It looks like you have forgotten that the ma between form and divName should be enclosed in quotes. Instead of

...' + form,divName + '...

do

...' + form + ',' + divName + '...
发布评论

评论列表(0)

  1. 暂无评论