• js 重写a标签的href属性和onclick事件


    适应场景:假如移动端拨打电话,需要给a标签添加href属性,但是由于需求,需要链接跳转的同时给a标签添加onclick事件,如果不做任何处理的话,默认执行点击事件,而不会跳转href属性的链接。

    怎么解决:重写a标签的href属性和onclick事件

    //这段代码可放入点击事件里

    (function(){

    this.fnCancel();
    var _event_list = {};
    // 找到页面上所有的a标签
    var links = document.getElementsByTagName("a")[0];
    // 保存click属性的值
    var _click = links.getAttribute("onclick");
    // 保存href属性的值
    var _href = links.getAttribute("href");
    if (_click != null) {
    // 给onclick属性重新设值
    links.setAttribute("onclick", "eval_a_click_event('a')");
    }
    if (_href != null) {
    // 给href属性重新设值
    links.setAttribute("href", "javascript:eval_a_href_event('a')");
    }
    _event_list["a"] = [links, _href, _click];

    })()

    function eval_a_href_event(id) {
    var link = _event_list[id];
    if (link != null && link[1] != null) {
    // 拿到href属性的值
    alert(link[1]);
    // 将href属性值重新赋回原来的值
    link[0].setAttribute("href", link[1]);
    // 移除单击事件
    link[0].removeAttribute("onclick");
    // 模拟单击事件
    link[0][0].click();
    // 重写href属性的值
    link[0].setAttribute("href", "javascript:eval_a_href_event('" + id + "')");
    // 如果有单击事件,重新加上
    if (link[2] != null) {
    link[0].setAttribute("onclick", link[2]);
    }
    }
    }
    function eval_a_click_event(id) {
    var link = _event_list[id];
    if (link != null && link[2] != null) {
    // 拿到单击事件的方法
    alert(link[2]);
    // 执行单击事件
    eval(link[2]);
    }
    }
  • 相关阅读:
    数据结构与算法(3-4)--矩阵的压缩存储
    数据结构与算法(3-3)--队列的应用
    数据结构与算法(3-2)--栈的应用
    数据结构与算法(3-1)--栈和队列
    数据结构与算法(2)--线性表(数组和链表)
    数据结构与算法(1)--时间及空间复杂度
    python变量与地址的关系
    python高级(03)--socket编程
    python高级(02)--生成器和迭代器
    python处理http接口请求
  • 原文地址:https://www.cnblogs.com/huoerheaven/p/9391703.html
Copyright © 2020-2023  润新知