簡體   English   中英

在$ .html插入的內容上使用JQuery?

[英]Using JQuery on $.html inserted content?

我已經在我的網站上創建了一個表單,並使用JQuery根據先前的選擇顯示/隱藏元素並添加更多字段。 這很好。

從此繼續,我希望JQuery在用戶使用onclick($。html)單擊鏈接時將此表單動態插入DOM中。 這也一切正常。 當用戶單擊鏈接時,該鏈接的表單立即顯示在頁面上。

但是,當表單加載$ .html時,我的其他JQuery語句(顯示/隱藏元素等)不再起作用。

我們可以在JQuery $ .html插入的元素上使用JQuery嗎?

可以將事件分配給使用jQuery創建的DOM元素。 沒有代碼(您應該始終提供),我不能肯定地說,但是我想您正在覆蓋以前具有事件處理程序的元素。

只要有可能, .append()新HTML而不是覆蓋它,那么您就無需重新分配事件。 如果確實需要制作新元素,那么您有兩種解決方案:

  1. 重新分配事件處理程序
  2. 使用事件委托在第一個父對象上設置事件處理程序,該事件處理程序不會被覆蓋

有關更多信息請參見jQuery的.on() ,但一般語法為:

$("#always-element").on("click", ".overwritten-elem-selector", function() {
    // work
});

這是一個簡單的例子(JSFiddle)

JS

var nums = 1;

$("#more").on("click", function() {
    var $newElem = $("<div></div>").text(++ nums);        
    $("#foo").html($newElem);
});

$("#foo").on("click", "div", function() {
    $(this).css("background-color", "#FF0000");
});

HTML

<button id="more">More</button>
<div id="foo">
    <div>1</div>
</div>

是的,您可以在插入到DOM中的標記上使用jQuery,但是必須確保將內容插入到頁面中之后(而不是插入之前 )綁定該代碼

要詳細說明並演示我認為的問題,請考慮以下小提琴http://jsfiddle.net/47wVQ/

您在DOM中有一些插入元素的位置:

<div id="testTarget"></div>

還有一些JS:

var elemBefore = $('<p id="thingToInteractWith">BEFORE</p>');

$('#thingToInteractWith').on('click', function(){
    $(this).hide();
});

$('#testTarget').append(elemBefore); //At this point, the element is in the DOM

//Below is what should be done instead
var elemAfter = $('<p id="anotherThingToInteractWith">AFTER</p>');

//Binding AFTER element exists

$('#testTarget').append(elemAfter); //At this point, the element is in the DOM

//Here I'm binding the click action after the markup is in the DOM
$('#anotherThingToInteractWith').on('click', function(){ 
    $(this).hide();
});

長話短說,如果您要向DOM中插入新內容(例如您的表單),並且想要顯示/隱藏等內容來處理該新內容,請確保在使用$ .html之后觸發JS。

在您的特定示例中,這看起來像:

function bindEvents(){
   //This assumes you have form elements with the following IDs
   $('#myFormElement1').on('change', function(){ $(this).hide() });
   $('#myFormElement2').on('change', function(){ $(this).hide() });
}

var $form; //We'll pretend this variable holds the markup for your form
$('#target').html($form); //Your form is now in the DOM
bindEvents(); //Since myFormElement1..2.. now exist, they can be interacted
//with and so calling bindEvents after the $.html call will work

暫無
暫無

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

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