如何使用“ onClick”功能获取元素的ID

时间:2019-02-16 10:02:17

标签: javascript jquery

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

1 个答案:

答案 0 :(得分:1)

代替

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