降低<a href=" ">的执行速度

kai*_*er2 4 html javascript css jquery

在我的网站上,我有多个href's,我需要在它们被点击和加载之间添加延迟.因为有数百个hrefs我不能为每个单独的js功能.

我研究的两种方法是将href的内容作为变量传递给javascript,例如:

<a href="example1.php">example1</a>
<a href="example2.php">example2</a>
<a href="example3.php">example3</a>
<script>
var href = ### CONTENTS OF SELECTED HREF ###
$(function() {
  $("a").on("click", function(event) {
    event.preventDefault();
    setTimeout(function(){window.location.href = href;}, 1000);
  });        
});
Run Code Online (Sandbox Code Playgroud)

是否可以使用CSS这样做?

voi*_*oid 6

不,这是不可能使用CSS(层叠样式表,没办法).你需要使用Javascript.

但是,是的,您不需要为每个函数编写不同的函数a,只需获取href单击回调内部,然后相应地重定向用户.

$(function() {
  $("a").on("click", function(event) {
    event.preventDefault();
    var href = this.href;
    setTimeout(function(){
        window.location = href;
    }, 1000);
  });        
});
Run Code Online (Sandbox Code Playgroud)