2017-05-14 52 views
0

當點擊一個鏈接我修改這個代碼,以確認打開頁面不是別人:JQuery的 - 上鍊接點擊()函數承認一些聯繫,但

<a href="http://google.com" id="check">Visit Google!</a> 

<script> 
$('#check').click(function(e) { 
e.preventDefault(); // Prevent the href from redirecting directly 
var linkURL = $(this).attr("href"); 
warnBeforeRedirect(linkURL); 
}); 

function warnBeforeRedirect(linkURL) { 
swal({ 
title: "このリンク開けますか?", 
text: "If you click 'OK', you will be redirected to " + linkURL, 
type: "warning", 
showCancelButton: true 
}, function() { 
// Redirect the user 
window.location.href = linkURL; 
}); 
} 
</script> 

此代碼剪斷的作品非常好,因爲它是嵌入在我的index.php頁面。但是,如下所示的另一個代碼片段:

<a href='/classreg.php?studentid=<?php echo $row["studentid"]; ?>&classid=<?php echo $row["classID"]; ?>&furikae=2&class_time=<?php echo $datecheck; ?>' class="btn btn-warning" id="check"> 
<span class="glyphicon glyphicon-hand-right"></span>欠席 
</a> 

不起作用。第一個鏈接調用該函數,而第二個鏈接不調用該函數。

我認爲一定要獲得被識別的id標籤的方式,但我不確定如何去調試這個,因爲我對JS和JQuery相對較新。

如果我忘記添加任何重要信息,請讓我知道。

謝謝。

回答

2

使用class選擇器代替id選擇器。您不能將相同的ID設置爲多個元素。這是您的第一個鏈接工作而其他人沒有的問題。

所以你的代碼應該看起來像這樣

<a href="http://google.com" class="check" id="check">Visit Google!</a> 

和第二HREF

<a href='/classreg.php?studentid=<?php echo $row["studentid"]; ?>&classid=<?php echo $row["classID"]; ?>&furikae=2&class_time=<?php echo $datecheck; ?>' class="btn btn-warning check" id="check1"> 

和JS使用$('.check')代替$('#check')

+0

謝謝!這很有道理,現在我覺得很愚蠢。當我使用class進行引導格式化時,類選擇器如何工作?你會注意到我的第二個鏈接有class =「btn btn-warning」它應該改爲class =「btn btn-warning check」嗎? –

+0

是的,你可以設置多個類到一個元素。 –

+0

@BenjaminJones另一方面,你可以改變第二個爲'id =「check1」'並使用選擇器'$('a [id^= check]')'而不是'$('#check')'..這兩種方式將與您合作 –