当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Pop up menu opens new tab instead of continuing in the same tab

问题描述:

I have some code where I click on pop up menu button, then menu appears and when I do next .click() on menu element, it tries to open new tab with the AJAX link from the menu option but I want to use it as user would, then it would do the trick in the same tab, without opening new. Is there any way to make browser think that user clicked that?

HTML

<a class="_54nc" href="/ajax/groups/members/remove.php?group_id=xxx&amp;uid=xxx" rel="dialog-post" role="menuitem">

<span>

<span class="_54nh">Remove from group</span>

</span>

</a>

JS

array = $('a._54nc').get();

array[0].click();

So basicly, if user would click that link, the next popup on the same tab would be showed, but when I do this with javascript, it tries to open the AJAX link in new tab witch ends with failure.

网友答案:

If you have content script loaded in the browser's tab, then you can create a mouse event and then trigger the event to replicate the effect of user clicking the dom

/**
* create mouse event and dispatch
* param {string} type     event name
* param {DOM Element} el  DOM element on which event will trigger
*/
function triggerMouseEvent (type, el) {
    var myEvent = new MouseEvent(type, {
        'view': window,
        'bubbles': true,
        'cancelable': true
    });
    el.dispatchEvent(myEvent);
}

var array = $('a._54nc').get();
var element = array[0];
triggerMouseEvent('mousedown', element);
triggerMouseEvent('mouseup', element);

Second solution

If you want to open the url in same window, then you can change the location of window. (as pointed out by @some-non-descript-user in the comments)

var uri = element.getAttribute('href');
self.location.href = uri;

Another thing you can do is to insert the iframe in your page with the same url.

var myFrame = '<iframe src='+uri+' width="'+window.innerWidth+'" height="'+window.innerHeight+'" style="position:absolute;"></iframe>';
$('body').append(myFrame);

and you can hide the rest of the dom

分享给朋友:
您可能感兴趣的文章:
随机阅读: