如何在JQuery中动态更改URL

时间:2017-05-31 10:26:11

标签: jquery

我是JQuery的新手!我知道如何在点击时将按钮从关注更改为取消关注但我需要网址(在按钮中)在Spring中调用我的ResponseEntity而我不知道该怎么做.... < / p>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
    button {
        padding: 5px 10px;
        font-size: 14px;
    }
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $("button").click(function(){
            $(this).text($(this).text() == 'Follow' ? 'Unfollow' : 'Follow');
            $('a').attr('href',($(this).text() == 'Follow' ? 'FollowUrl' : 'UnFollowUrl');
        });
    });
</script>
</head>
<body>

    <button type="button">Follow</button><a href="/firsttime" id="url">Follow</a>

<p><strong>Note:</strong> HINT: Click the button to swap the text and the URL.</p>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

检查您网页上生成的html,并根据其外观更改javascript代码。

例如,您可以制作2个链接(标记:)切换可见性,如下所示:

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script type="text/javascript">
  $(document).ready(function() {
    //all <button>s on page that are clicked:
    $("button").click(function() {
      //Switch text on button.
      $(this).text($(this).text() == 'Follow' ? 'Unfollow' : 'Follow');

      //Select all links (tag <a>) on page.
      $('a').toggle(); //toggle display: none/initial (visibility)
    });
  });
</script>

<!-- links that are going to be switched visibility -->
<a href="/follow" style="display:none;">follow</a>
<a href="/unfollow">unfollow</a>

<!-- button that has the event listener click in javascript code above -->
<button type="button">Follow</button>
<p><strong>Note:</strong> Click the button to swap the text and the URL.</p>
&#13;
&#13;
&#13;

另一种选择是替换html标记中的href属性:

// select element - change attr - chose attribute (href in this case) - set new value
$('YourSelectorHere').attr('href','NewLinkHere');