Send Div id to javascript via onclick

醉酒当歌 提交于 2019-12-20 11:54:12

问题


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

回答1:


Here is a jQuery answer

  <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>



回答2:


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>



回答3:


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

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



回答4:


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

<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.




回答5:


How about passing this.id to the javascript function?



来源:https://stackoverflow.com/questions/3389657/send-div-id-to-javascript-via-onclick

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