在打开超链接之前改变它的链接地址
Change href to https://console.upyun.com/register/?invite=rylCq7Shr
before open it.
In other words, I'd like to open https://console.upyun.com/register/?invite=rylCq7Shr
rather than https://www.upyun.com/?utm_source=lianmeng&utm_medium=referral
when click it.
Here is the elements structure:
<p><a href="https://www.upyun.com/?utm_source=lianmeng&utm_medium=referral"
target="_blank" rel="sponsored"><img src="https://example.com/assets/upyun-logo.png"
alt="又拍云" class="footer-logo"></a></p>
Solutions
a. 监听超链接元素的鼠标悬停事件。
[mouseenter - Web API 接口参考 | MDN]1
(() => {
const upyunLogo = document.querySelector('img.footer-logo[alt=又拍云]');
upyunLogo && (upyunLogo.parentElement.onmouseover = () => {
upyunLogo.parentElement.href = 'https://console.upyun.com/register/?invite=rylCq7Shr';
});
})();
b. 监听超链接元素的点击事件。
(() => {
const upyunLogo = document.querySelector('img.footer-logo[alt=又拍云]');
upyunLogo && (upyunLogo.parentElement.onclick = () => {
upyunLogo.parentElement.href = 'https://console.upyun.com/register/?invite=rylCq7Shr';
});
})();
Conclusion
mouseover
和 click
都属于可冒泡事件,所以将事件直接绑定在某元素上,可监听本身及子元素的事件。
- 不需要判断实际触发事件的 event target,直接定位到元素改变其属性即可。
References
- https://developer.mozilla.org/zh-CN/docs/Web/API/Element/mouseenter_event.