[英]jQuery selector for target event?
我有以下CSS和HTML :
a { padding: 20px; } div { background: yellow; margin: 600px 0; }
<a href="#target_id_1">link 1</a> <a href="#target_id_2">link 2</a> <a href="#target_id_3">link 3</a> <a href="#target_id_4">link 4</a> <a href="#target_id_5">link 5</a> <div id="target_id_1" class="target_class">I'm the target 1!</div> <div id="target_id_2" class="target_class">I'm the target 2!</div> <div id="target_id_3" class="target_class">I'm the target 3!</div> <div id="target_id_4" class="target_class">I'm the target 4!</div> <div id="target_id_5" class="target_class">I'm the target 5!</div>
當目標為“ target_class”類的div
時,我想執行某些jquery操作。
我知道,可以通過向這些a
標簽添加一個通用類(例如“ link” ),然后將click事件處理程序與該類綁定,來實現以下目的:
$(".link").click(function(){
//code
});
我需要知道的是: 是否有針對特定類/ id的目標事件的jQuery處理程序?
就像是:
$(".target_class").target(function(){
//code
});
如果沒有,是否有其他選擇可以實現?
選擇器( a[href^="#target"]
)的工作方式與每個<a>
標記匹配,該標記的href
以#target
。
$('a[href^="#target"').click(function(){ alert('You targeted something.'); });
a { padding: 20px; } div { background: yellow; margin: 600px 0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <a href="#target_id_1">link 1</a> <a href="#target_id_2">link 2</a> <a href="#target_id_3">link 3</a> <a href="#target_id_4">link 4</a> <a href="#target_id_5">link 5</a> <div id="target_id_1" class="target_class">I'm the target 1!</div> <div id="target_id_2" class="target_class">I'm the target 2!</div> <div id="target_id_3" class="target_class">I'm the target 3!</div> <div id="target_id_4" class="target_class">I'm the target 4!</div> <div id="target_id_5" class="target_class">I'm the target 5!</div>
我認為這個事件在js中不存在,但是您可以處理哈希更改:
$(window).on('hashchange', function(){
if ( $(this.location.hash).hasClass('target_class') ){
// do stuff
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.