gpt4 book ai didi

javascript - 使用 Javascript 将 href 替换为 onclick

转载 作者:行者123 更新时间:2023-11-30 11:18:02 25 4
gpt4 key购买 nike

我想用 .example-class 类更改每个 anchor 并将其 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= 之前的所有内容,包括 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>

关于javascript - 使用 Javascript 将 href 替换为 onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50837744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com