通过 onclick 将 Div id 发送到 javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3389657/
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-08-23 04:24:19  来源:igfitidea点击:

Send Div id to javascript via onclick

javascripthtmlonclick

提问by richsoni

I have a page with several div's. All of the divs have a unique id. I would like to send that id to a javascript function. I have tried to save it as a value as well, and send this.value, but that does not work either.

我有一个包含多个 div 的页面。所有的 div 都有一个唯一的 id。我想将该 id 发送到 javascript 函数。我也尝试将它保存为一个值,并发送 this.value,但这也不起作用。

<div class='recordElem$val' id='$rname' value='$rname'
onclick='javascript:updateRecord(this.value);'>
        $name</div>"

回答by Brandon Boone

Here is a jQuery answer

这是一个 jQuery 答案

  <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>

  <script type="text/javascript">
   function clicked(item) {
    alert($(item).attr("id"));
   }
  </script>


  <div onclick="clicked(this);" id="test">test</div>

回答by Arun P Johny

Have a look at two ways to solve this problem

看看解决这个问题的两种方法

<html>
<body>
    <div id="scopeId" onclick="javascript:testScope.call(this)">Using scope</div>
    <div id="parameterId" onclick="javascript:testId(this.id)">Using Parameter</div>
    <script>
        function testScope(){
            alert("Scope: " + this.id)
        }
        function testId(id){
            alert("Parameter: " + id)
        }
    </script>
</body>
</html>

回答by Robusto

Use onclick="updateRecord(this)"and handle it like this:

onclick="updateRecord(this)"像这样使用和处理它:

function updateRecord(div) {
  // statements
  var id = div.id; // or however you want to use the id
  // statements
}

回答by adil hashmi

You can assign php variables value to javascript variable value. Then you can use it onclick example:

您可以将 php 变量值分配给 javascript 变量值。然后你可以使用它 onclick 示例:

<script language="javascript">
    var a=<?php echo $tabs['menu_id']; ?>

    </script>

    <a href="index.php" onclick="show_center(a);">pass it</a>

Here we can pass javascript's variable to function.

在这里,我们可以将 javascript 的变量传递给函数。

回答by Henk

How about passing this.id to the javascript function?

将 this.id 传递给 javascript 函数怎么样?