javascript - JS operation to open a new page will be intercepted, how to solve it?
高洛峰
高洛峰 2017-06-30 09:56:28
0
8
891

There is an onclick event for a button on the page. Clicking triggers js and sends an ajax request to the background. After a series of judgments, the background returns the url to js

<a class="a" id="k_id" href="javascript:void(0);" onclick="test($(this),id1,id2);"></a>
function test(){
    //发送ajax请求...返回一个url
    var url = "ajax请求返回的url";
    
    //js操作将返回的url赋值到页面上的a标签,然后js模拟a标签点击事件
    $(oElement).attr("href",url);
    $(oElement).removeAttr("onclick");
    var id = $(oElement).attr("id");
    document.getElementById(id).click();//这里点击a标签
    
    //这样的操作会被浏览器拦截,
}

求解

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(8)
曾经蜡笔没有小新

You can jump directly to the url. Why do you want to simulate a click? Direct window.location.href = url

洪涛

onclick monitors the click event, so it triggers the call to the test method first, and then calls it repeatedly, but the herf jump cannot be triggered

漂亮男人

After sending ajax, there is no need to simulate a tag click event, just set location.href = the URL that needs to be jumped

给我你的怀抱

When jumping to the page, there is no need to remove the onclick event of a;
If you need to remove it, the current method is directly t.onclick = null; and you can

<a class="a" id="k_id" href="javascript:void(0);" onclick="test(this)">123123</a>
function test(t) {
    var url = "http://www.baidu.com";
    t.setAttribute("href", url);
    t.onclick = null;
    t.click();
}
某草草

You can try it
Open a new page: window.location.href = url;
Open a new window: window.open(url);

ringa_lee

Isn’t it better to use window.location.href directly?

世界只因有你

The

a tag has a default click event. It is estimated that onClick conflicts with the default event.

漂亮男人

Because there are asynchronous operations, the browser will intercept window.open().

You can change ajax to synchronization, or find a way to calculate the url on the front end.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template