javascript 我想在onc​​lick中传递两个参数,一个是函数,另一个是div id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31695970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:11:56  来源:igfitidea点击:

I want to pass two parameters in onclick, one is a function & another is a div id

javascript

提问by Debabrata Roy

I want to sen two id's when onclick occurs like now when div 2 is clicked I want to pass just the id of the 2nd div too & then write script for the 2nd div. is it possible? if so, then how? any example?

我想在 onclick 发生时发送两个 id,就像现在单击 div 2 时一样我也想只传递第二个 div 的 id,然后为第二个 div 编写脚本。是否可以?如果是这样,那怎么办?任何例子?

<div id="1st_div"></div>
<div id="2nd_div">
     <div id="inner_of_2nd_div" onclick="myfunction('1st_div')"></div>
</div>

采纳答案by Veverke

You can pass as many parameters as you wish. Just define the function accordingly.

您可以根据需要传递任意数量的参数。只需相应地定义函数。

For instance, for a 2 parameters function myFunction, your onclick should look like

例如,对于 2 个参数的函数 myFunction,您的 onclick 应该如下所示

onclick="myfunction(p1, p2)"

and your function myFunction like

和你的功能 myFunction 像

myfunction(p1, p2) {
  //do your stuff

}

回答by 3pic

I understand that you want a function which has id argument of the clicked div. If right, use JQuery and do that:

我知道您想要一个具有被点击 div 的 id 参数的函数。如果正确,请使用 JQuery 并执行以下操作:

HTML:

HTML:

<script src="http://code.jquery.com/jquery-1.11.3.min.js"/> 
<div id="1st_div" class="clickable"></div>
                <div id="2nd_div" class="clickable">
                     <div id="inner_of_2nd_div" ></div>
                </div>

JS Jquery:

JS 查询:

$(".clickable").click(function(){
        var _id=$(this).attr("id");
        alert("I am div id="+_id+" and I've been clicked right now!");
    });

回答by Suvradip Saha

        <div id="1st_div"></div>
<div id="2nd_div">
     <div id="inner_of_2nd_div" onclick="myfunction(document.getElementById('1st_div'));">asa</div>

<script>
function myfunction(obj)
{
//here i caught the object 
obj.innerHTML=obj.id;
}
</script>