我想用类.example-class
更改每个锚点并从
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
,这会有效吗?
答案 0 :(得分:3)
使用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>
答案 1 :(得分:0)
您可以使用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);
}
&#13;
<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>
&#13;
答案 2 :(得分:0)
在现代浏览器中,我可能会在这行中写一些东西,在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}`));
});
答案 3 :(得分:0)
替代运行所有链接并更改它们:
$('.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);
}
&#13;
<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/>
&#13;