2014-12-08 79 views
1

我有這樣的代碼:如何知道jQuery中哪個錨點被點擊?

HTML:

<ul class="dropdown-menu" role="menu" id="document_dropdown"> 
    <li><a class="notify" href="toSomewhere" id="1">Item1</a></li> 
    <li><a class="notify" href="toSomewhere" id="2">Item1</a></li> 
    <li><a class="notify" href="toSomewhere" id="3">Item1</a></li> 
    <li><a class="notify" href="toSomewhere" id="4">Item1</a></li> 
</ul> 

JQuery的:

$(document).ready(function() { 
    $('#document_dropdown .notify').click(function(){ 
     var id = $(this).attr("id"); 
     alert(id); 
    }); 
}); 

我想實現的是看到的是點擊哪個錨並返回一個錨,這樣的id我可以在另一個腳本中使用它。到目前爲止,它什麼都不做。我的代碼可能有什麼問題?誰能幫我這個?非常感謝你。

回答

5

你的代碼將正常工作,雖然this.id是從元素中檢索一個原生屬性的更簡潔的方法。如果您希望停止點擊導致瀏覽器發出HTTP請求的鏈接,則需要將preventDefault()添加到您的邏輯。

您不能從事件處理程序返回任何東西,這樣反而如果你需要傳遞的信息圍繞你需要或者其存儲在一個全局變量,或調用另一個函數,用該值作爲參數。

$('#document_dropdown .notify').click(function(e){ 
    e.preventDefault(); 
    var id = this.id; 
    alert(id); 
    doSomething(id); 
}); 

function doSomething(id) { 
    alert('You clicked #' + id); 
} 

Example fiddle

+0

感謝您的幫助和榜樣。 – Paul 2014-12-08 08:00:19

+0

沒問題,很樂意幫忙。 – 2014-12-08 08:01:11

1

你只需要做到這一點:

$(document).ready(function() { 
    $('#document_dropdown .notify').click(function(){ 
     var id = this.id; 
     alert(id); 
    }); 
}); 

完蛋了。

+0

這在邏輯上是不從什麼OP已經在做不同的,除了他的使用jQuery對象,而不是在'this'本土元素參考的'id'財產。 – 2014-12-08 07:46:09

1

事件處理程序不能返回任何東西。您需要調用另一個腳本函數並將ID作爲參數傳遞。

$(document).ready(function() { 
$('#document_dropdown .notify').click(function(evt){ 
    var id = this.id; 
    alert(id); 
    anotherScriptFunction(id); 
    evt.preventDefault(); 
}); 
}); 
+1

謝謝。但即使使用preventDefault(),它仍然會重定向到href中的頁面。 – Paul 2014-12-08 07:50:52

+0

然後只需添加HREF Item1 2014-12-08 07:52:41

1

你可以通過在這樣的事件處理程序:

$(document).ready(function() { 
    $('#document_dropdown .notify').click(function(e){ 
     var id = e.target.id; 
     alert(id); 
    }); 
}); 

這樣,e.target是你已經點擊的元素。你可以通過$(e.target)將它包裝成一個jQuery元素。

相關問題