简体   繁体   English

目标事件的jQuery选择器?

[英]jQuery selector for target event?

I have the following CSS and HTML : 我有以下CSSHTML

 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> 

I want to perform certain jquery operations when div s with class "target_class" are targeted. 当目标为“ target_class”类的div时,我想执行某些jquery操作。

I know this can be achieved by adding a common class to these a tags (say, "link" ) and then binding a click event handler with that class like this: 我知道,可以通过向这些a标签添加一个通用类(例如“ link” ),然后将click事件处理程序与该类绑定,来实现以下目的:

$(".link").click(function(){
    //code
});

What I needed to know was: Is there a jQuery handler for target event for a particular class/id? 我需要知道的是: 是否有针对特定类/ id的目标事件的jQuery处理程序?

Something like: 就像是:

$(".target_class").target(function(){
   //code
});

If not, are there any alternatives to achieve this? 如果没有,是否有其他选择可以实现?

The way this works is the selector ( a[href^="#target"] ) matches every <a> tag whose href begins with #target . 选择器( 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> 

I think this event does not exist in js, but you can handle hash change : 我认为这个事件在js中不存在,但是您可以处理哈希更改:

$(window).on('hashchange', function(){
   if ( $(this.location.hash).hasClass('target_class') ){
      // do stuff
   }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM