[英]JQuery links to open new window
我正在嘗試通過從瀏覽器內移至單獨的彈出窗口來改進為網站創建的音樂播放器,創建/操縱了代碼,發現使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>
或者使用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");
});
});
使用data-*
屬性比在ID中存儲歌曲和藝術家數據更好。
<a href="this_page.cfm?song=1" target="_blank" class="playSong" data-info="#artist# - #song#">Play Track</a>
.preventDefault()
或return false;
如果啟用了Javascript,可用於阻止瀏覽器跟蹤鏈接:
$(".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;
});
單擊鏈接后,您需要給return false。 如下 :
$(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;
});
});
這是您問題的實際完整答案
如果禁用了JavaScript或激活了彈出窗口阻止程序,如何使鏈接在新窗口中工作
$(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
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.