I am trying to capture the ID of the element being clicked when a user clicks on an element which allows him to leave a page. The idea is to then record this using Ajax. The script below seems to be working fine as long as the element has an ID, but it does not seem to be able to climb the DOM to find an ancestor's ID if it has not. What am I doing wrong?

我试图捕获当用户点击允许他离开页面的元素时被点击的元素的ID。我们的想法是使用Ajax记录它。只要元素有ID,下面的脚本似乎工作正常,但是如果它没有,它似乎无法爬上DOM来查找祖先的ID。我究竟做错了什么?

$(document).ready(function(){
    $('a, button, input[type=submit]').on('click', function (event) {
        if (event.target.id == '')
            alert($(this).closest('[id!=""]').attr('id'));

        else
            alert(event.target.id);
    });
});

4 个解决方案

#1


1

if the parent's id is not defined or the element is nested so much that you can't count how many parents it has, i.e. get the closest parent's id that actually has an id, then this code will do the job for you: DEMO

如果未定义父级的id或者元素嵌套太多以至于无法计算它拥有多少个父级,即获得实际具有id的最接近的父级id,则此代码将为您完成工作:DEMO

$(document).on('click', 'a, button, [type="submit"]', function() {

    if($(this).attr('id') === undefined || $(this).attr('id') === null) {
        alert($(this).parents().filter(function(){
            return $(this).attr('id')!=undefined && $(this).attr('id')!=null;
        }).attr('id'));
    } else {
         alert($(this).attr('id')); 
    }

});

更多相关文章

  1. Yii - 加载ajax表单元素的用户端验证
  2. 删除后重新插入后保留对元素的引用
  3. jquery中获取相邻元素相关的命令:next()、prev()和siblings()
  4. 如何选择两个h2之间的所有元素
  5. 千呼万唤 HTML 5 (2) - 区块元素
  6. 在中的元素的自定义子弹符号,这是一个普通字符,而不是一个图像
  7. JQuery选择器和操作得到的元素
  8. 是否有更快的方法来遍历HTMLDocument中的每一个元素呢?
  9. 在PHP中获取幕布元素ID的文本[重复]

随机推荐

  1. android度量相对于地球坐标系的加速度
  2. Android base64 上传图片
  3. Android Studio第六期 - 横向GridView
  4. android的k歌
  5. Android--遍历SQLite数据库下的所有表名
  6. EditText
  7. Android--取得布局中指定控件的宽高
  8. Android取得系统信息和分辨率内存信息
  9. 删除android ScrollView边界阴影方法
  10. Android ListView二三事