【问题标题】:how to identify li item using jquery如何使用jquery识别li项目
【发布时间】:2011-05-11 06:53:31
【问题描述】:

我有一个清单

<ul>
  <li><a href="?page=4">one</li>    //no 4
  <li><a href="?page=7">two</li>    //no 7
  <li><a href="?page=14">three</li>  //no 14
  <li><a href="?page=72">four</li>   //no 72
  <li><a href="?page=201">five</li>   //no 201
</ul>

现在我想使用 ajax 来加载页面而不是正常的页面加载。那么如何检测用户使用 jQuery 点击了哪个链接。像这样说

$('id of the element clicked').click(function()({ 
      // Load the page using .ajax() 
});

在上面的jQuery代码中,我如何得到id of the element clicked??

【问题讨论】:

  • 在你的 html sn-p 中没有一个元素有id。顺便说一句,你可以使用$(this).attr('href')
  • 还没有.. 我可以分配那个。我以为我可以像 id="1" 一样分配,但说 id 不能以整数开头
  • 所以如果我使用$(this).attr('href'),那么 1) 它是否仍会重新加载页面,因为标记中仍然存在href 值; 2) 如果我得到?page=id 字符串,如何使用ajax 加载页面?我是否使用 .load() 之类的东西?

标签: jquery


【解决方案1】:

您可以使用正则表达式从单击的锚点的href 属性中获取 id:

$('ul a').click(function() {
    var id = this.href.match(/([0-9]+)$/)[1];
    // Load the page using .ajax()  
});

但是恕我直言,一种更好的方法是使用 HTML5 data-* 属性,而不是使用正则表达式来解析 url:

<ul>
  <li><a href="?page=4" data-id="4">one</li>
  <li><a href="?page=7" data-id="7">two</li>
  <li><a href="?page=14" data-id="14">three</li>
  <li><a href="?page=72" data-id="72">four</li>
  <li><a href="?page=201" data-id="201">five</li>
</ul>

然后:

$('ul a').click(function() {
    var id = $(this).data('id');
    // Load the page using .ajax()  
});

其他一些答案建议使用id 属性,但将id="4" 添加到锚点将是无效标记,因为根据规范,DOM 元素的 id 不能以数字开头。

【讨论】:

  • data-id 与旧版浏览器是否存在兼容性问题??
  • @ptamzz,请定义旧浏览器。我会推荐你​​modernizr。你也可以看看following question
【解决方案2】:

不需要 id,使用$(this) ;)

例如:

$("li").click(function(){
  $(this).//do ajax stuff
});

如果你想获得点击元素的href:$(this).children('a').attr('href')

【讨论】:

  • 这基本上是正确的;但是, li 需要用引号引起来: $("li").click(...
【解决方案3】:

您可以像这样获取&lt;a&gt;id 属性:

$("ul>li>a").click(function(){
   // the id of the anchor
   alert($(this).attr('id'));
   // the id of the li
   alert($(this).parent().attr('id'));
   // link's page id
   alert($(this).attr('href').match(/page=(\d+)$/));
});

【讨论】:

  • 他想要列表项的 id,而不是锚点。
【解决方案4】:

要获取 id,首先将 id 分配给您的 li,然后尝试这个...

$('li').click(function(){

      $(this).attr('id') ;
});

【讨论】:

    【解决方案5】:

    有点晚了,但你不能这样做吗:

    $(function() {
        $('ul li').each(function() {
            $('a', this).click(function(e) {
                e.preventDefault();
                var href = $(this).attr('href');
                $('#somediv').load(href);
            });
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-23
      • 2011-06-17
      • 2012-04-06
      • 2020-04-17
      • 2011-06-12
      • 2020-02-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多