簡體   English   中英

使用Javascript用onlick替換href

[英]Using Javascript to replace a href with onlick

我想用類.example-class更改每個錨點並從中更改其href

href="https://www.example.com/?fsaction=doSomething&id=123"

onClick="myFunction('id=123')"

有點像

$('.example-class').each(function() {
  var href = $(this).attr('href');
  var idOnly = (href -remove everything before and including id=);
  $(this).attr('onclick', "id='" + idOnly + "'")
  .removeAttr('href');
});

我怎樣才能“刪除所有內容,包括id =”以獲得123 ,這將有效嗎?

使用URL

 $('.example-class').each(function() { var href = $(this).attr('href'); var idOnly = (new URL(href)).searchParams.get("id"); $(this).attr('onclick', "myFunction('id=" + idOnly + "')") .removeAttr('href'); }); function myFunction(id) { console.log(id); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="example-class" href="https://www.example.com/?fsaction=doSomething&id=123">Here</a> 

你可以使用href.split('&')[1].split('=')[1]來獲取id值:

 $('.example-class').each(function() { var href = $(this).attr('href'); var idOnly = href.split('&')[1].split('=')[1]; $(this).attr('onclick', "myFunction('"+idOnly+"')") .removeAttr('href'); }); function myFunction(id){ console.log('id is ' + id); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class = 'example-class' href="https://www.example.com/?fsaction=doSomething&id=123">click me</a> 

在現代瀏覽器中,我可能會在這行中寫一些東西,在vanilla javascript中:

document.querySelectorAll("a.example-class").forEach(a => {
  const params = new URLSearchParams(a.search);
  const id = params.get("id");
  a.removeAttribute("href");
  a.addEventListener("click", myFunction.bind(a, `id=${id}`));
});

替代運行所有鏈接並更改它們:

 $('.example-class').on("click",function(e) { e.preventDefault(); // cancel the link var href = $(this).attr('href'); var idOnly = (new URL(href)).searchParams.get("id"); // from https://stackoverflow.com/a/50837858/295783 myFunction("id=" + idOnly); }); function myFunction(id) { console.log(id); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="example-class" href="https://www.example.com/?fsaction=doSomething&id=123">123</a><br/> <a class="example-class" href="https://www.example.com/?fsaction=doSomething&id=456">456</a><br/> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM