首页 > 解决方案 > 如何使用'onClick'函数获取元素的id

问题描述

我正在尝试使用“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>

标签: javascriptjquery

解决方案


代替

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


推荐阅读