国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

return false;和e.preventDefault();的區別

2019-11-21 00:22:03
字體:
來源:轉載
供稿:網友
Have you ever seen those two things (in the title) being used in jQuery? Here is a simple example:
復制代碼 代碼如下:

$("a").click(function() {
$("body").append($(this).attr("href"));
return false;
}

That code would append the href attribute as text to the body every time a link was clicked but not actually go to that link. The return false; part of that code prevents the browser from performing the default action for that link. That exact thing could be written like this:
復制代碼 代碼如下:

$("a").click(function(e) {
$("body").append($(this).attr("href"));
e.preventDefault();
}

So what's the difference?


The difference is that return false; takes things a bit further in that it also prevents that event from propagating (or “bubbling up”) the DOM. The you-may-not-know-this bit is that whenever an event happens on an element, that event is triggered on every single parent element as well. So let's say you have a box inside a box. Both boxes have click events on them. Click on the inner box, a click will trigger on the outer box too, unless you prevent propagation. Like this:

演示地址:http://css-tricks.com/examples/ReturnFalse/
So in other words:
復制代碼 代碼如下:

function() {
return false;
}

// IS EQUAL TO

function(e) {
e.preventDefault();
e.stopPropagation();
}

It's all probably a lot more complicated than this and articles like this probably explain it all a lot better.


參考:

1.The difference between ‘return false;' and ‘e.preventDefault();'
2.Event order

測試代碼打包下載

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 夏津县| 柏乡县| 驻马店市| 洪雅县| 高安市| 仁寿县| 西城区| 抚州市| 左权县| 静宁县| 阳城县| 霍山县| 襄城县| 项城市| 松滋市| 兴国县| 西林县| 五莲县| 盖州市| 海晏县| 禹州市| 寿阳县| 中西区| 阜城县| 乐陵市| 民乐县| 衡南县| 钟山县| 蓝田县| 克什克腾旗| 泾源县| 甘肃省| 兴隆县| 鹤壁市| 蒲城县| 兴安县| 分宜县| 昌吉市| 胶州市| 屯留县| 栾川县|