我想控制鏈接是否可點擊或是否應顯示錯誤(基于 ajax 呼叫的結果)。
<a class="lnkCustomer" href="http://localhost/viewcustomer" target="_blank" data-customerno="237">View</a>
我到了可以將鏈接設定為“允許點擊”的地步:
// Authorized
anchor.data("authorized", true);
但是,當我運行此代碼時,鏈接仍然無法打開。理想情況下,一旦 ajax 呼叫完成,它應該呼叫 click 事件。我相信問題出在這一行。
// Trigger Anchor
anchor.click();
這是整個代碼:
<script type="text/javascript">
$(".lnkCustomer").click(function(e)
{
var customerNo = $(this).data('customerno');
var anchor = $(this);
// Check for authorized
if (anchor.data("authorized"))
{
return true;
}
$.ajax(
{
url: 'http://localhost/checkcustomer',
type: 'POST',
dataType: 'json',
data: { customerNo: customerNo },
cache: false,
success: function (result)
{
if (result.success)
{
// Authorize
anchor.data("authorized", true);
// Trigger Anchor
anchor.click();
}
else
{
// Show a message in a alert or div
alert('Not authorized');
}
}
});
// Default to false (Do not process anchor)
return false;
});
</script>
注意:我在錨點中使用 class 而不是 id 因為我有各種鏈接會觸發此事件。但是,正如您所看到的,這應該不是問題,因為我總是指單個物件:
var anchor = $(this);
uj5u.com熱心網友回復:
我認為我們不能覆寫錨標記的默認行為,但我們可以解決它。在此解決方案中,我已替換href為data-link. 并用 模仿錨點機制window.open。
代碼 :
<a class="lnkCustomer" data-link="http://localhost/viewcustomer1" data-customerno="111" data-auth>View</a>
<a class="lnkCustomer" data-link="http://localhost/viewcustomer2" data-customerno="237" data-auth>View</a>
<a class="lnkCustomer" data-link="http://localhost/viewcustomer3" data-customerno="237" data-auth>View</a>
<script type="text/javascript">
$(".lnkCustomer").click(function (e) {
var customerNo = $(this).data('customerno');
var linkToGo = $(this).data('link');
var anchor = $(this);
// Check for authorized
if (anchor.data("authorized")) {
var win = window.open(linkToGo, '_blank');
}else{
$.ajax(
{
url: './checkcustomer.php',
type: 'POST',
data: { customerNo: customerNo },
cache: false,
success: function (result) {
if (result == 'authorized') {
anchor.data("authorized", true);
var win = window.open(linkToGo, '_blank');
}
else {
// Show a message in a alert or div
alert('Not authorized');
}
}
});
}
});
</script>
請注意 :
- 您可以使用 CSS 來設定錨標記的樣式,我在解決方案中沒有
- 我嘗試過的一種方法是使用
preventDeault,但它不起作用
uj5u.com熱心網友回復:
您沒有阻止顯示的默認事件。嘗試使用e.preventDefault()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/372159.html
標籤:javascript html 查询 阿贾克斯
上一篇:視口中的影片數字-使用逗號
下一篇:g組元素不在svg中從0,0開始
