簡體   English   中英

jQuery無法識別html元素的ID

[英]jquery doesn't recognize an id of html element

我不知道為什么#btn上的jQuery click事件不起作用。

`//this is the script` 
$('document').ready(function(){
  $('#btn').click(function(){
    alert('2');
  });
});

function appendToPopUp(){
  document.getElementById('popUp').innerHTML='<BUTTON id="btn" onClick="alert(1)">clickerIci</BUTTON>';
}

<!--this is the body-->
<DIV id='popUp'></DIV>
<BUTTON onClick='appendToPopUp()'>display</BUTTON>

這里有兩個問題:

$('document').ready(...

應該:

$(document).ready(...

然后,您將動態插入btn按鈕。 由於它在document.ready上不可用,因此根本沒有附加該事件。 您必須在appendToPopUp內部重新附加事件。

function appendToPopUp()
{
  document.getElementById('popUp').innerHTML='<BUTTON id="btn" onClick="alert(1)">clickerIci</BUTTON>';

  $('#btn').click(function(){
    alert('2');
  });
}

因此,在這種情況下,您實際上不需要$(document).ready()

編輯

實際上要做的是這樣的:

<DIV id='popUp'></DIV>
<BUTTON id="display">display</BUTTON>

$(document).ready(function() {
  $('#display').on('click', function() {
    $('#popUp').html('<BUTTON id="btn">clickerIci</BUTTON>');

    $('#btn').on('click', function() {
      alert('2');
    });
  });
});

參見JSFiddle

Try with the below HTML...
On page load Jquery doesn't know about #btn so it will not bind the events so we explitcly calling the bindevents function after it is loaded to DOM.

<script>
function bindevents(){
    $('#btn').on("click",function(){
          alert('2');
    });
}
function appendToPopUp()
{
  document.getElementById('popUp').innerHTML='<BUTTON id="btn"   onClick="alert(1)">clickerIci</BUTTON>';
   bindevents();
}
</script>
<DIV id='popUp'></DIV>
<BUTTON onClick='appendToPopUp()'>display</BUTTON>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM