jQuery - 更改href attr

时间:2014-05-31 08:28:36

标签: javascript jquery html href attr

我试图通过jQuery更改href,但我不知道为什么它不起作用...

$(document).ready(function () {
  var oldurl = $('`http://google.com`');
  var newurl = $('`http://yahoo.com`');

  $('a[href="' + oldurl + '"]').attr('href', newurl);

  // it's not working too...
  //$('a[href="http://google.com"]').attr('href', 'http://yahoo.com');

  // it's not working too...
  //$('.mylink').attr('href', newurl);
});

JSFiddle

1 个答案:

答案 0 :(得分:6)

你只需要:

var oldurl = 'http://google.com';
var newurl = 'http://yahoo.com';
$('a[href="' + oldurl + '"]').attr('href', newurl);

Demo

网址必须是字符串,而不是jQuery个对象,而您忘记关闭方括号。