使用javascript在新标签页中打开链接会停止工作

时间:2015-07-11 07:08:13

标签: javascript jquery html css tumblr

我的tumblr博客上有一些代码使得“notes”div中的链接在新标签中打开 - 它工作正常但是一旦我点击“显示更多笔记”(加载更多链接),它就会停止致力于这些链接。这是我的代码。

<script type="text/javascript">
$(function(){
  $("#notes a").attr("target","_blank");
});
</script> 

这是tumblr在这个问题上所说的:“Notes是用AJAX分页的。如果你的主题需要操作Notes标记或DOM节点,你可以添加一个新的Javascript回调。 Notes页面已加载或插入“

tumblrNotesLoaded(notes_html)“如果定义了这个Javascript函数,它将在加载新的Notes页面并准备插入时触发。如果此函数返回false,它将阻止插入的注释。“

tumblrNotesInserted()“如果定义了这个Javascript函数,它将在将一个新的Notes页面插入DOM后触发。”

3 个答案:

答案 0 :(得分:1)

新加载的链接不会将目标设置为_blank ...当您加载新链接时应该执行的操作是

$("#notes a").attr("target","_blank"); 

再次 - 因为你没有显示关于加载这些链接的代码,这是我能做的最好的

编辑:我只看了你的页面 - 我 想想 这应该做的伎俩

this.style.display = 'none';
document.getElementById('notes_loading_121152690941').style.display = 'block';
if (window.ActiveXObject) var tumblrReq = new ActiveXObject('Microsoft.XMLHTTP');
else if (window.XMLHttpRequest) var tumblrReq = new XMLHttpRequest();
else return false;
tumblrReq.onreadystatechange = function() {
    if (tumblrReq.readyState == 4) {
        var notes_html = tumblrReq.responseText.split('<!-- START ' + 'NOTES -->')[1].split('<!-- END ' + 'NOTES -->')[0];
        if (window.tumblrNotesLoaded)
            if (tumblrNotesLoaded(notes_html) == false) return;
        var more_notes_link = document.getElementById('more_notes_121152690941');
        var notes = more_notes_link.parentNode;
        notes.removeChild(more_notes_link);
        notes.innerHTML += notes_html;
        if (window.tumblrNotesInserted) tumblrNotesInserted(notes_html);
        // ************************************************
        $("#notes a").attr("target","_blank");
        // ************************************************
    }
};
tumblrReq.open('GET', '/notes/121152690941/lhtXynZtK?from_c=1433902641', true);
tumblrReq.send();
return false;

添加的行被// ************************************************

包围

答案 1 :(得分:1)

您可以在target委托事件上设置mousedown属性,例如:

$(function () {
    $('#notes').on('mousedown', 'a:not([target])', function () {
        this.target = "_blank";
    });
});

答案 2 :(得分:0)

使用此:

$('ol.notes').on('click', 'a', function (e) {
    if (e.which > 1 || e.shiftKey || e.altKey || e.metaKey || e.isDefaultPrevented()) {
        return;
    }
    window.open(this.href);
    e.preventDefault();
});

这会在notes容器上附加一个事件处理程序,确保它只获得a个元素的点击,并且点击不是中间点击,alt-clicks,...

一旦过滤掉所有这些多余的点击,它只需通过Javascript打开一个新标签页;没有必要设置target="_blank"

相关问题