0

I have this scenario. In my HTML page, when click on an a element, I load some HTML and jQuery content as string, and change a div's content (via innerHTML) to this new text.

Here is the jQuery code:

<script type="text/javascript">
    $("a.accessor").click(function(event) {
        var cId = this.id;
        $.get("/video/" + cId)
        .done(function(data){
            var contentDiv = document.getElementById("navigator");
            contentDiv.innerHTML = data;
        })
        .fail(function(data) {
            alert("An error occured during request. Please try again later!");
        });
    });
</script>

The problem is that after this jQuery code runs, the new jQuery code (that replace this one), does not respond.

Bellow is the new HTML/jQuery code that I get:

<div class="breadcrumb">
    <a href="/video">Competitors</a>
    <span>&gt;</span>
    <a href="#">Name</a>
</div>
<div class="video-browser">
    @for(v <- competitor.getVideos()) {
        <div class="folder">
            <a id="@(competitor.getId())_@v.getId()" class="accessor">
                <img src="@routes.Assets.at("images/movie_file.png")" />
                <span>@v.getVideoName()</span>
            </a>
        </div>
}
<script type="text/javascript">
    $("a.accessor").click(function(event) {
        alert(123);
    });
</script>

Obs. I put some code related to my framework that I use for the sake of conciseness.

Having the HTML/jQuery above, when I try to click on an a element I get nothing. Can anybody explain me why this?

If you need more details, ask me for, please.

Thanks in advance!

4

2 回答 2

1

将您的脚本更改为此...

<script type="text/javascript">
    $("a.accessor").click(function(event) {
        var cId = this.id;
        $.get("/video/" + cId)
            .done(function(data){
                $("#navigator").html(data);
            })
            .fail(function(data) {
                alert("An error occured during request. Please try again later!");
            });
    });
</script>

它使用 jQuery 的html()方法来添加新的 html(和脚本),这将执行脚本,这与您之前使用的方法不同。

于 2013-10-02T10:36:13.537 回答
-1

这是因为您的单击事件处理程序未初始化。您需要将其包装在文档就绪块中。然而...

<script type="text/javascript">
$(function(){
    $("a.accessor").click(function(event) {
        alert(123);
    });
});
</script>

也不会工作,因为 a 标签不在 DOM 中。最好使用委托。这将为 .accessor 中的所有标签添加一个点击处理程序,将来添加时也是如此。将此代码放在您的主 html 中。

$(function(){
    $(".accessor").on('click', 'a',function(event) {
        alert(123);
    });
});
于 2013-10-02T10:32:59.577 回答