简体   繁体   English

使用Javascript用onlick替换href

[英]Using Javascript to replace a href with onlick

I would like to change every anchor with class .example-class and change its href from 我想用类.example-class更改每个锚点并从中更改其href

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

to

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

Something along the lines of 有点像

$('.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');
});

How can I "remove everything before and including id=" to get just 123 and will this work? 我怎样才能“删除所有内容,包括id =”以获得123 ,这将有效吗?

Use URL 使用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> 

You can use href.split('&')[1].split('=')[1] to get the id value only: 你可以使用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> 

In modern browsers I would probably wrote something among this line, in vanilla javascript: 在现代浏览器中,我可能会在这行中写一些东西,在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}`));
});

Alternative to running over all links and change them: 替代运行所有链接并更改它们:

 $('.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