Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
简单jquery/javascript开关href_Javascript_Jquery_Html_Class_Href - Fatal编程技术网

简单jquery/javascript开关href

简单jquery/javascript开关href,javascript,jquery,html,class,href,Javascript,Jquery,Html,Class,Href,我有这个链接: <div name="top"> <!-- some code --> <a class="myLinkToTop" href="#bot">Click</a> <!-- some code --> <div name="bot"> 但我有两个问题: 当我单击链接时,它的href会发生变化,但该操作会将我发送到#top,而不是#bot 之后,我希望href在#top和#bot之间切换。我不知道

我有这个链接:

<div name="top">
  <!-- some code -->
  <a class="myLinkToTop" href="#bot">Click</a>
  <!-- some code -->
<div name="bot">
但我有两个问题:

  • 当我单击链接时,它的
    href
    会发生变化,但该操作会将我发送到#top,而不是#bot
  • 之后,我希望
    href
    在#top和#bot之间切换。我不知道怎么做,所以我想用“toggleclass()”更改我的类值,但我认为这不是解决我的问题的最佳方法

这将移动到当前href on链接,然后更改它:

$(".myLinkToTop").click(function(e){ 
    e.preventDefault();
    window.location.href = this.href;
    this.href = this.hash === "#top" ? "#bot" : "#top";
 });

正如Banana所说,您可以使用
if/else
语句检查当前
href
值。如果当前值为
#bot
,则在1秒后将其设置为
#top
(这将允许首先通过原始值)。如果当前值为
#top
,则反之亦然

$(".myLinkToTop").on("click", function () {
    var $this = $(this), // cache "this as a jQuery object"
        href = $this.attr("href");

    if (href === "#bot") { 
        setTimeout(function () {
            $this.attr("href", "#top"); 
        }, 100);
    } else {
        setTimeout(function () {
            $this.attr("href", "#bot"); 
        }, 100);
    }
});

单击该链接时,您是否试图转到页面顶部?不,我希望先转到#bot,但单击同一链接后,我将正常转到#top。然后,当我点击我的链接时,我可以返回#bot等。我明白了,所以您希望切换这两个?为什么不根据当前值在HREF之间切换
if-else
?每次单击此链接时,我都希望在其上切换“href”属性。但是,当我尝试使用我的简单示例时,“href”属性会更改,但在我移动之前,位置也会更改。我不知道你是否理解我的英语不是很好为什么不使用这个。href?谢谢,我更了解这个脚本。我不知道它是否更好,但更容易理解。@ll这首先阻止默认处理程序单击链接执行,然后移动到顶部或底部,然后检查哈希是否设置为“顶部更改为顶部”。
$(".myLinkToTop").on("click", function () {
    var $this = $(this), // cache "this as a jQuery object"
        href = $this.attr("href");

    if (href === "#bot") { 
        setTimeout(function () {
            $this.attr("href", "#top"); 
        }, 100);
    } else {
        setTimeout(function () {
            $this.attr("href", "#bot"); 
        }, 100);
    }
});