【问题标题】:dynamically loaded content click event not firing动态加载的内容点击事件未触发
【发布时间】:2014-01-15 21:18:24
【问题描述】:

目前,我正在通过下拉点击事件(通过 jquery 事件)动态加载 HTML 出现的问题是我的 .on 事件函数没有找到选择器来触发“a”标签点击事件。 如果加载的原始页面包含带有指定类的“a”标签的html,则该“a”标签的点击事件可以正常工作,但是如果我通过jquery事件动态加载新内容,那么如果一个可点击的“a "标签存在并且我点击它,原始页面只是回发,没有证据表明"a"标签点击事件触发。

这里是动态加载内容的示例;

<div id="recipedirectionsandimage">
    <div id="recipedirections">
        <h2 class="recipedirectionsheader"> Recipe Directions</h2>
        <ol class="recipesteps">
            <li>Pre-Heat oven to 350°, Grease two 9" springform pans</li>
            <li>Sift all dry ingredients into a large bowl</li>
            <li>Add corn oil, eggs and vanilla, mix well</li>
            <li>Fold in walnuts, coconut, carrots and pineapple</li>
            <li>Pour batter into the greased pans</li>
            <li>Bake for 50 minutes on the middle racks</li>
        </ol>                    
        <p>Click&nbsp;<a ID="creamcheesefrosting.txt" class="icing" 
            href="#">here</a>&nbsp; for frosting recipe</p>
    </div>
    <div id="recipeimage">
        <img src="Images/RecipeImages/carrotcake_160x233.png" alt=""/>
    </div>
</div>

这是内容的加载方式,通过 WCF 服务检索 html,我已确认该服务正在运行;

function resetRecipeHtml(html, recipename) {
$("#lblRecipeLegend").text("Recipe for " + recipename);
$("#recipecard").html(html);

}

这是 jquery 事件代码,目前此代码只是在文档就绪代码之外的页面上的脚本块中(如果它在其中也不起作用)注意:警报仅用于证明事件正在开火。;

 $('#recipedirections p').on('click', 'a.icing', function (e) {
      e.preventDefault();
      var filename = $(this).attr("id");
      alert(filename);
      getRecipeHtml(filename);          
  });

【问题讨论】:

  • 我试了一下,原来没有,现在也没有。
  • 请显示动态创建内容的代码
  • 而且段落当然不是动态插入的,#recipedirections也不是,因为你委托给的父级必须是静态的
  • 对不起。没有必要。我错过了“这是动态加载内容的示例”。别人回答了
  • adeneo....正确,我必须从插入的内容中取出一个父母,现在它被解雇了,谢谢。将其发布为答案,我会接受它

标签: javascript jquery events


【解决方案1】:

您的部分问题

这里是动态加载内容的示例;

<div id="recipedirectionsandimage">
    <div id="recipedirections">

因为,recipedirections 也是动态加载内容的一部分。您应该使用document 或最近的静态容器。你应该使用recipecard

 $("#recipecard").on('click', 'a.icing', function (e) {
      e.preventDefault();
      var filename = $(this).attr("id");
      alert(filename);
      getRecipeHtml(filename);          
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2017-08-07
    • 1970-01-01
    相关资源
    最近更新 更多