2012-07-30 57 views
2

我有一個div,其內容會從innerHTML的動態生成,我似乎無法針對使用jQuery進行驗證這些元素從innerHTML的或.html()設置元素,例如,這是網頁:如何指定使用jQuery

<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US"> 
<head> 
</head> 
<body> 
<span id="alert1">Alert1</span> 
<input type="button" value="Click Me" id="button1" /> 
<div id="empty"></div> 
</body> 
</html> 

,這是js代碼:

<script type = "text/javascript"> 
    $(document).ready(function() { 
     $('#button1').click(function() { 
      var html = "uname <input type='text' id='uname'><br />password <input type='text' id='password'><br /><span id='alert'>Alert</span>"; 
      $('#empty').html(html); 
     }); 
     $('#alert').click(function() { 
      alert('Alert'); 
     }); 
     $('#alert1').click(function() { 
      alert('Alert1'); 
     }); 
    }); 
</script>​ 

與ID alert1的作品跨度但ID警報的警報,其使用的innerHTML或.html()不工作,那麼如何解決這一問題設定?

預先感謝您

回答

3

的這裏的問題是,當你寫這樣的..

$("#element").click(function() { 
     alert("Alert!"); 
    }); 

..它只會造成當你執行的代碼中存在的元素的事件處理程序。即使它們具有相同的jQuery選擇器(本例中爲「#element」),它也不會爲將來的元素創建事件處理程序。

您需要做的事情是在父元素上綁定.on(event, selector, function),因爲事件會「向上冒泡」層次結構。這樣你可以處理來自指定選擇器的未來事件。個人而言,我會做這樣的:

$(document).ready(function() { 
    $('#button1').click(function() { 
     var html = "<insert lots of html stuff here>"; 
     $('#empty').html(html); 
    }); 

    $(document).on("click", "#alert", function() { 
     alert("Alert!"); 
    }); 

    $(document).on("click", "#alert1", function() { 
     alert("Alert1!"); 
    }); 
});​ 
0

你必須附上聽衆AFTHER您添加的對象到DOM!

所以afther .html(...)

<script type = "text/javascript"> 
$(document).ready(function() { 
    $('#button1').click(function() { 
     var html = "uname <input type='text' id='uname'><br />password <input type='text' id='password'><br /><span id='alert'>Alert</span>"; 
     $('#empty').html(html); 
     $('#alert').click(function() { 
      alert('Alert'); 
     }); 
    }); 

}); 

.on()也是一種選擇。如果將偵聽器呈現給dom,則獨立綁定偵聽器。但我推薦第一種方法。如果您正在編寫更大的應用程序,創建後附加處理程序的方法會更清晰,那麼事件委託自動附加事件處理程序可能甚至不會發現。 1或2個是好的,但如果您要添加多個事件,多個對象(變量,類),你可以失去監督......

0

使用事件委託綁定單擊處理程序,使用.on()

 $('#empty').on('click', '#alert1', function() { 
     alert('Alert1'); 
    }); 

或者您可以在創建內容後綁定處理程序。

1

你應該使用委託

$(elements).delegate(selector, events, data, handler); 

按你的代碼

$(document).ready(function() { 
    $("yourdiv").delegate("#alert, #button, #Alert1", "click", function() { 
    alert('Alert'); 
    }); 
});