为动态插入的HTML运行javascript函数

Run javascript function for dynamically inserted HTML

本文关键字:运行 javascript 函数 HTML 动态 插入      更新时间:2023-09-26

我有一段代码,在另一个元素的悬停位置插入下面的代码。

<div class="star" id="1">
<div class="star" id="2">
<div class="star" id="3">
<div class="star" id="4">
<div class="star" id="5">
</div>
</div>
</div>
</div>
</div>

所有我想做的是检索每个DIV的ID通过javascript:

$(document).ready(function() {
$('.star').on(function(e){
    e.stopPropagation();
    var rating = $(this).attr('id');
    alert(rating);
});
});

我已经尝试了很多方法来实现这个,这是我最近尝试的,但我仍然没有运气!如有任何帮助,我将不胜感激

添加div时触发事件

var counter = 0;
$(someelement).on("mouseenter",function(){
    counter++;
    $('<div class="star" id="' + counter + '" />').appendTo(".star:last").trigger("staradded");
})
$(document).on("staradded",".star",function(e) {
    alert(this.id);
});

或者更好的是,跳过这个事件。

var counter = 0;
$(someelement).on("mouseenter",function(){
    counter++;
    $('<div class="star" id="' + counter + '" />').appendTo(".star:last");
    alert(counter);
})

我会使用"livequery"插件- https://github.com/brandonaaron/livequery

如果我理解正确的话,你需要一些像"live"这样的旧函数,因为你想看所有新的。明星"元素。

在本例中,您只需使用以下代码:

 $('.star').livequery('click',function(e){});

你可以在那里找到一个简单的例子- http://jsfiddle.net/WEr5J/11/

您的wrong语法为on,因为您不是telling,您想绑定什么事件。在绑定所需的事件后,例如单击,您可以使用映射函数获得star类的elements的所有逗号分隔的id。

Live Demo

$(document).on('click', '.star', function(e) {
    e.stopPropagation();
    ids = $('.star').map(function() {
        return this.id;
    }).get().join();
    alert(ids);
});

您需要使用each来遍历所有元素。

$('.star').each(function(){           
    var rating = $(this).attr('id');    
    alert(rating);
});
​