无法选择在jQuery中动态附加的按钮

时间:2015-01-02 16:02:37

标签: javascript jquery jquery-selectors

我在jQuery中使用getJSON函数,并在DOM中以按钮的形式追加检索到的结果。但是我不能在附加的DOM上使用选择器。

这是我的剧本:

$.getJSON("http://example.com/checkDiary.php?babyID=" + localStorage.getItem("babyRegNo"), function(data) {
            if (data.indexOf("noDiary") > -1) {
                document.getElementById("diaryList").innerHTML = "<p>Your baby currently has no diary entry.</p>";
            } else {
                var appendedText = '';
                $.each(data, function(){
                    var diaryID = this.diary_id;
                    var dateAdded = this.date;
                    appendedText = appendedText + '<p><button type="button" class="diaries" value ="' + diaryID + '">' + dateAdded + '</button></p>';
                })
                document.getElementById("diaryList").innerHTML = appendedText;
            }
        })

这是我用来选择:

$(':button.diaries').click(function(){});

但它似乎无法正常工作。但是,当我在HTML正文中放置一个具有相同类的虚拟按钮时,它被完美地选中。你们能给我任何建议吗?

2 个答案:

答案 0 :(得分:0)

检查您的代码是否在文档准备好之后

 $(document).ready(function(){ //your code here });  

并使用

$('button.diaries').on(click , function(){}) 

而不是 .click

答案 1 :(得分:0)

@Kelvin Aliyanto ....所以解决方案将是这样的

<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script>
$(function(){
        $.getJSON("http://example.com/checkDiary.php?babyID=" + localStorage.getItem("babyRegNo"), function(data) {
            if (data.indexOf("noDiary") > -1) {
                document.getElementById("diaryList").innerHTML = "<p>Your baby currently has no diary entry.</p>";
            } else {
                var appendedText = '';
                $.each(data, function(){
                    var diaryID = this.diary_id;
                    var dateAdded = this.date;
                    appendedText = appendedText + '<p><button type="button" class="diaries" value ="' + diaryID + '">' + dateAdded + '</button></p>';
                })
                document.getElementById("diaryList").innerHTML = appendedText;
            }
        });


        $('div').on('click', '.diaries', function(event){
        alert("Hi");
        }) ;

});
</script>   

<div id="diaryList"></div>