javascript - .click() 函数被忽略

标签 javascript jquery html

我正在生成无序列表中的列表项。然后我想听听对这些列表项中的任何一个的点击。我知道我还没有发布完整的代码,但我希望我没有必要这样做。我的 jQuery 单击函数是否完全忽略了像这样附加的元素?我已经尝试了几乎所有方法,但找不到原因!我只想看到我的“哈哈”警报! :(

  $.each(entries, function(i, v) {
    s += '<li';
    if (favouriteItem(v.title)) s += ' data-theme="e"';
    s += '><a href="#feedItemPage" class="contentLink" data-transition="slide" data-entryid="'+i+'">' + v.title + '</a></li>';
  });

  $("#linksList").append(s);
  $("#linksList").listview("refresh");

    $("li").click(function() {
      alert("lol");
      selectedEntry = $(this).data("entryid");
    });

虽然这些项目确实在视觉上出现了,但源代码仍然是这样的:

  <div data-role="content">
      <ul data-role="listview" id="linksList" data-divider-theme="b" data-inset="false"></ul>
  </div>

表明那里没有 li 元素。然而,它们确实在视觉上显示出来了吗?在我跳入熔岩池之前,请有人救救我。

最佳答案

改变:

$("li").click(function() {
  alert("lol");
  selectedEntry = $(this).data("entryid");
});

$('#linksList').on('click', 'li',function() {
  alert("lol");
  selectedEntry = $(this).data("entryid");
});

动态添加元素到文档时,需要使用.on()'s委托(delegate)事件语法。

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page.

关于javascript - .click() 函数被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16905105/

相关文章:

html - IE 6 中的 float LI

javascript - 最小化 puppeteer 时我的代码不运行

javascript - MongoDB 中的映射减少 : undefined is not a function

javascript - 无法验证表单是否已使用 CasperJS 和 jQuery 填写

javascript - 在主干js View 中调用oneview到另一个 View 没有出现

html - iFrame 上的隐藏文本

javascript - 如何使用模糊事件从元素中删除函数名称?

jquery - 如何使用jquery获取wordpress中的当前页面id

jquery - 如果我将 "on"与 jQuery 一起使用,我是否需要将此函数包含在准备好的文档中?

html - 超链接图像的背景颜色问题