简体   繁体   English

如何在动态加载内容中的链接上绑定“点击”?

[英]How to bind `click` on links in dynamic loading content?

I have some weird problem.我有一些奇怪的问题。 Let's assume we have an HTML page with the following code:假设我们有一个 HTML 页面,其代码如下:

<div class="description">
        <a href='#' class='oldkeenload btn btn-apply' data-subject='1' data-subject2='3'><i class="fa fa-cloud-download" aria-hidden="true"></i> Загрузить материал</a>
</div>

When user clicks the href button with the class oldkeenload I do the following js code:当用户单击带有 class oldkeenload 的 href 按钮时,我执行以下 js 代码:

$(".oldkeenload").click(function () {
    // console.log("Clicked");
    var topic=$(this).data('subject');
    var kcode=$(this).data('subject2');

    var datastring = '/app/server.php?oldkeen=' + kcode + '&topicid=' + topic;

    // console.log(datastring);

    // var parentTag = $( this ).parent().get( 0 ).tagName;
    // console.log("Parent tag: " + parentTag);

    $(this).parent(".description").load(datastring);

    return false;
});

It just loads the response from the server to the "description" div.它只是将来自服务器的响应加载到“描述”div。 I do this to avoid loading all the materials, letting user load what he needs in one specific category.我这样做是为了避免加载所有材料,让用户在一个特定类别中加载他需要的东西。 User sees intro to the material, presses the load button, the contents load.用户看到材料介绍,按下加载按钮,加载内容。

However, when you load with this method the new links in the loaded content fails to load new contents.但是,当您使用此方法加载时,已加载内容中的新链接无法加载新内容。 When I click the link nothing happens.当我单击链接时,没有任何反应。

Any idea how to do it in JS without server side scripting?知道如何在没有服务器端脚本的情况下在 JS 中执行此操作吗?

The jQuery .load() function accept an extra callback. jQuery .load () function 接受额外的回调。 It will be run after the load is done.它将在加载完成后运行。 You can bind the click function again after the DOM is updated by .load .您可以在 .load 更新 DOM 后再次绑定click .load

var loadData = function () {
    // console.log("Clicked");
    var topic=$(this).data('subject');
    var kcode=$(this).data('subject2');

    var datastring = '/app/server.php?oldkeen=' + kcode + '&topicid=' + topic;

    // console.log(datastring);

    // var parentTag = $( this ).parent().get( 0 ).tagName;
    // console.log("Parent tag: " + parentTag);
    var $container = $(this).parent(".description");
    $container.load(datastring, function () {
        $(".oldkeenload", $container).click(loadData);
    });

    return false;
}
$(".oldkeenload").click(loadData);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM