使用jQuery防止div内所有链接的默认值 [英] prevent default for all links inside a div using jquery

查看:75
本文介绍了使用jQuery防止div内所有链接的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的div看起来像这样:

I have a div that looks like:

<div id="blah"> <a href="#" >hello</a>   <a href="#"> world</a></div>

我想使用e.preventDefault();禁用此div中的所有链接.

I want to disable all the links inside this div using e.preventDefault();

如何使用jquery选择div id ="blah"内的所有href标签?

How can I select all href tags that are inside the div id="blah" using jquery?

推荐答案

以下内容将为您提供<div>中ID为blah且已定义href属性的所有<a>元素.

The following will get you all <a> elements inside <div> with id blah that have a href attribute defined.

$('#blah a[href]').click(function(e) { e.preventDefault(); });

在没有jQuery的情况下,类似于以下(我显然一直生活在jQuery世界中,因为我最初在原始JavaScript中使用了preventDefault.不幸的是,不是跨浏览器:()确实在Firefox,IE和Chrome中对此进行了测试

without jQuery, something like the following (I've obviously been living in jQuery world far too long as I originally had preventDefault in the vanilla JavaScript. Unfortunately, not cross-browser :( ) I did test this in Firefox, IE and Chrome

var anchors = document.getElementById('blah').getElementsByTagName('a');

for(var i=0; i < anchors.length; i++) {
    addEvent(anchors[i], 'click', preventDefault);
}

function preventDefault(e) {
    e = e || window.event;
   (e.preventDefault)? 
       e.preventDefault() : e.returnValue = false;
}

function addEvent(obj, evType, fn){ 
   if (obj.addEventListener){ 
       obj.addEventListener(evType, fn, false); 
       return true; 
   } 
   else if (obj.attachEvent){ 
       var r = obj.attachEvent("on"+evType, fn); 
       return r; 
 } else { 
       return false; 
 } 
}

出于兴趣,这是 jQuery 实现preventDefault()

// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
    preventDefault: function() {
        this.isDefaultPrevented = returnTrue;

        var e = this.originalEvent;
        if( !e )
            return;
        // if preventDefault exists run it on the original event
        if (e.preventDefault)
            e.preventDefault();
        // otherwise set the returnValue property of the original event to false (IE)
        e.returnValue = false;
    }

这篇关于使用jQuery防止div内所有链接的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆