繁体   English   中英

如何使用 jQuery 更改 html href 属性变量值?

[英]How to change html href attribute variable value with jQuery?

我正在尝试通过单击按钮将 html href 属性变量值 ?post=55 更改为 ?post=44 ,而不使用 jQuery 更改其他 URL 变量(thread=7),但不知道如何。

HTML

<button class="button">button</button>

<a href="posts.php?thread=7&post=55" class="post-link">Post</a>

JAVASCRIPT

$('.button').on('click', function() {

$("a").attr('href','posts.php?post=44') // this does not work because it removes ?thread=7
$("a").attr('href','posts.php?thread=7&post=44') // this also does not work because ?thread=7 is just a placeholder. I don't know what actual thread number is going to be.
  
});

这就是我所拥有的

<a href="posts.php?thread=7&post=55" class="post-link">Post</a> 

这就是我点击按钮时想要的

<a href="posts.php?thread=7&post=44" class="post-link">Post</a>
$('.button').on('click', function() {
   // Get the href Value:
   const link = $("a").attr('href'); // posts.php?thread=7&post=44
   // Split the href value by '&' (returns Array):
   const parts = link.split('&'); // ['posts.php?thread=7','post=44']
   // Get the actual post value (may not needed?)
   const post = parts.slice(-1)[0]; // post=44
   // remove the 'post=44' part:
   parts.pop() // ['posts.php?thread=7']
   // Important if more than one "&" in URL:
   const linkBase = parts.join('&');
   // Build the new URL including YOUR Post number:
   const newUrl = linkBase + '&post=n';
   
   $("a").attr('href', newUrl)

// Sources:
// https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/split
  
});

请注意,这是一个可以改进的示例,但它包含所有必要的步骤以更好地跟进。

希望能帮助到你

要执行您需要的操作,您可以向prop()提供一个函数(注意:不是attr() *),它接受当前属性值作为参数。 从那里您可以使用正则表达式来查找当前href中的数字并替换它。

使用此方法的好处是,无论post参数出现在 URL 中的哪个位置,它都可以工作。

同样在以下示例中,我将要设置的页面值存储为button上的data属性,但可以对其进行修改以适合您的特定用例。

 $('.button').on('click', function() { $('a').prop('href', (i, href) => href.replace(/(post=)\d{1,2}/, '$1' + $(this).data('page'))); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script> <button class="button" data-page="44">Update post to '44'</button> <a href="posts.php?thread=7&post=55" class="post-link">Post</a>

*请参阅此答案,了解为什么应该使用prop()而不是attr()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM