【问题标题】:Cannot change href value of a tag无法更改标签的 href 值
【发布时间】:2017-07-27 23:54:33
【问题描述】:

我正在尝试更改我的 href 值,但它似乎根本没有改变。 jQuery 和 javascript 方法我都试过了,都不管用。

<a type="button" class="view_me btn btn-primary" href="#">View Full</a>
$(document).on("click", ".click_row", function (e) {
  e.preventDefault();
  var _self = $(this);
  userId = _self.data('id');
  var newLink = '/users/view/' + userId //I'd like to eventually use this as new href link

  $(".view_me").prop("href", "www.google.com"); // Tried testing with a simple webpage

  // document.getElementById('view_test').href = "www.google.com"; // Tried this as well, doesn't work

  console.log(newLink)
});

任何建议都会有所帮助。我正在使用 jQuery 3.2.1

【问题讨论】:

  • www.google.com 不是有效的 URL。改用http://www.google.com
  • view_testclick_row 在哪里
  • &lt;a type="button" class="view_me btn btn-primary" href="#"&gt;View Full&lt;/a&gt; 没有 ID view_test
  • 添加minimal reproducible example html 以重现问题
  • 你需要将id="view_test"添加到你的锚元素

标签: javascript jquery href ejs


【解决方案1】:

有一些问题阻碍了预期的行为。首先,您的 click 函数没有被调用,因为它正在寻找 click_row 类;我相信您可能打算将其改为 view_me 类。 其次,您需要在 URL 的开头添加 https:// 以使其正确重定向。最后,您需要在代码中设置链接的href 属性,该链接的class view_me,而不是id view_me

编辑:另外,删除e.preventDefault(),否则您只能在新标签页中打开链接。

以下 JS 代码修复了这些问题并产生了所需的行为:

    $(document).on("click", ".view_me", function (e) {

        //e.preventDefault();

        var _self = $(this);
        userId = _self.data('id');

        var newLink = '/users/view/' + userId
        $(".view_me").prop("href", "https://www.google.com");

        console.log(newLink);

   });

工作 JSFiddle:https://jsfiddle.net/2m0297j1/

【讨论】:

  • 这很奇怪。我不能左键单击 a 标签,但是当我在另一个选项卡中打开它时它会起作用。感谢您的解决方案,但这里的最终目标是将 href 链接更改为参数。
  • 想通了。 e.preventDefault() 导致了奇怪的行为
  • 天哪,谢谢你
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-06
  • 2011-05-30
  • 1970-01-01
  • 1970-01-01
  • 2012-11-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多