我是Jquery和Javascript的新手。我试图在w3schools修改this示例,从最初的 www.w3schools.com 更改为第二个: www.w3schools.com/jquery 并在点击按钮时再次返回初始状态(根据需要多次),但我无法弄清楚如何做到这一点。请在答案中包含所有代码,这将更容易。感谢。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#w3s").attr("href", "https://www.w3schools.com/jquery");
});
});
</script>
</head>
<body>
<p>
<a href="https://www.w3schools.com" id="w3s">
W3Schools.com
</a>
</p>
<button>
Change href Value
</button>
<p>
Mouse over the link (or click on it) to see that the value of the href attribute has changed.
</p>
</body>
</html>
答案 0 :(得分:1)
您可以使用基本的if-else并检查href
属性。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var w3schoolURL = "https://www.w3schools.com";
if( $("#w3s").attr("href") === w3schoolURL )
$("#w3s").attr("href", "https://www.w3schools.com/jquery");
else
$("#w3s").attr("href", w3schoolURL);
});
});
</script>
</head>
<body>
<p><a href="https://www.w3schools.com" id="w3s">W3Schools.com</a></p>
<button>Change href Value</button>
<p>Mouse over the link (or click on it) to see that the value of the href attribute has changed.</p>
</body>
</html>
&#13;
答案 1 :(得分:1)
首先将您看到的链接悬停在... www.w3school.com
....点击button
链接更改后...您可以使用hover
链接进行检查。工作链接为toggle
https://www.w3schools.com/code/tryit.asp?filename=FGOSUXX5HUOG
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<p><a href="https://www.w3schools.com" id="w3s">W3Schools.com</a></p>
<button>Change URL</button>
<p>Mouse over the link (or click on it) to see that the value of the href attribute has changed.</p>
<script>
$(document).ready(function(){
$("button").click(function(){
var myURL = "https://www.w3schools.com";
if( $("#w3s").attr("href") === myURL )
$("#w3s").attr("href", "https://www.w3schools.com/jquery");
else
$("#w3s").attr("href", myURL);
});
});
</script>
</head>
<body>
</body>
</html>
&#13;
答案 2 :(得分:-1)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var w3 = "https://www.w3schools.com";
var w3Jquery = "https://www.w3schools.com/jquery";
var toggleFlag = true;
$("button").click(function(){
if(toggleFlag){
$("#w3s").attr("href", w3Jquery);
}
else{
$("#w3s").attr("href", w3);
}
toggleFlag = !toggleFlag;
});
});
</script>
<body>
<p><a href="https://www.w3schools.com" id="w3s">W3Schools.com</a></p>
<button>Change href Value</button>
<p>Mouse over the link (or click on it) to see that the value of the href attribute has changed.</p>
</body>