动态加载的内容点击事件未触发

时间:2013-12-28 13:12:56

标签: javascript jquery events

目前,我通过下拉点击事件动态加载HTML(通过jquery事件) 出现的问题是我的.on事件函数没有找到激活“a”标记点击事件的选择器。 如果加载的原始页面包含带有指定类的“a”标记的html,则该“a”标记的click事件可以正常工作,但是如果我通过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>

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

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);          
  });

1 个答案:

答案 0 :(得分:3)

您的部分问题

以下是动态加载内容的示例;

<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);          
  });
相关问题