1

我正在尝试通过从浏览器内移动到单独的弹出窗口来改进我为我的网站创建的音乐播放器,我已经创建/操作了我发现的代码以使 jQuery 采用 href 值并将它发送到一个新窗口,唯一的问题是点击<a>标签,它执行 href 点击和 jQuery 动作(就像它会做的那样)。我正在尝试找到一种有效的方法,以便如果用户禁用了 JavaScript,他们至少可以在新标签中使用音乐播放器,而不是根本无法收听,但我不确定如何去做这件事。将元素 href 设置为 var,然后删除 href 属性是否有效?或者这会导致错误吗?

示例 HTML:

<a href="this_page.cfm?song=1" target="_blank" class="playSong" id="#artist# - #song#">Play Track</a>

示例 jQuery:

<script type="text/javascript">
    $(document).ready(function(){
        $(".playSong").click(function(){
            var url = $(this).attr('href');
            var windowName = $(this).attr('id');

            window.open(url, windowName, "height=300,width=400");
        });
    });
</script>
4

4 回答 4

7

或者使用e.preventDefault()return false

$(document).ready(function(){
    $(".playSong").click(function(e){
        e.preventDefault(); // this will prevent the browser to redirect to the href
        // if js is disabled nothing should change and the link will work normally
        var url = $(this).attr('href');
        var windowName = $(this).attr('id');
        window.open(url, windowName, "height=300,width=400");
    });
});
于 2013-06-14T09:38:34.067 回答
1

Using a data-* attribute would be better than storing song and artist data in the ID.

<a href="this_page.cfm?song=1" target="_blank" class="playSong" data-info="#artist# - #song#">Play Track</a>

.preventDefault() or return false; can be used to stop the browser from following the link if Javascript is enabled:

$(".playSong").click(function(){
    var url = $(this).attr('href');
    var windowName = $(this).data('info'); // <-- using .data()

    window.open(url, windowName, "height=300,width=400");
    return false;
});
于 2013-06-14T09:40:50.947 回答
0

You need to give return false upon clicking the link. As follows :

    $(document).ready(function(){
        $(".playSong").click(function(){
            var url = $(this).attr('href');
            var windowName = $(this).attr('id');

            window.open(url, windowName, "height=300,width=400");
            return false;
        });
    });
于 2013-06-14T09:39:52.987 回答
0

Here is the actual complete answer to your questions

How to make the link work in a new window if javascript is disabled or a popup blocker is active

$(function(){
  $(".playSong").on("click",function(e){
    var w = window.open(this.href, this.target, "height=300,width=400");
    if (w) e.preventDefault(); // prevent link but only if not blocked
  });
});
于 2013-06-14T11:02:39.847 回答