繁体   English   中英

如何使用“onClick”函数获取元素的 id

[英]How to get id of an element with 'onClick ' function

我试图用“onClick”函数捕获一个整数 id。 并用ajax发送数据库。 并在警告框中显示与此 id 相关的所有信息。

<button class="show">Show Popup</button>

  <div class="Popup Confirm">
    <input type="text" id="id" />
    <button type="button" onclick="getId(document.getElementById('id').innerHTML);">Get</button>
  </div>

<script>
$('.show').click(function(){    
$(".Popup").show();
$("#id").val(4);
});

function getId(id = null) {
if(id) {        
    $.ajax({
        url: 'abc.php',
        type: 'post',
        data: {id: id},
        dataType: 'text',
        success:function(response) {
            alert(id);
        }
    }); 
} 
else {
    // error messages
     alert("No id selected");
    } 
  } 
</script>

代替

    <button type="button" onclick="getId(document.getElementById('id').innerHTML);">Get</button>

你应该使用:

    <button type="button" onclick="getId(document.getElementById('id').value);">Get</button>

输入字段值可通过value属性获得,而不是innerHTML

小提琴: https : //jsfiddle.net/3cjh6bf0/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM