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