I want to filter elements by delete system (on/off) in jQuery.Query.

Asked 2 years ago, Updated 2 years ago, 44 views

For example, if you do the following for jQuery's delete system (on/off), the click event will be triggered even in <form>.

 var selector = 'a, form';

$(document).on('click submit', selector, function(){
    // something
});

Would it be possible to invoke only the click events for var selector='a,form'; and only the click events for <a> and submit events for <form>?

By the way, I tried the following, but it didn't work.
(Both will be activated)

 var selector = 'a, form'; // This cannot be changed

$(document).on('click submit', selector, function(){
    // something
});

$(document).off('submit', 'a');//<a> wants to disable submit events
$(document).off('click', 'form');//<form> wants to disable click events

// This didn't work either.
$('a').off('submit');
$('form').off('click');

add

What I want to do is to create a plug-in that retrieves and displays other pages in ajax, and I want to support <a> tags (buttons) and <form>.
After retrieving the contents from ajax, if there are <a> or <form> among them, I would like to apply it as well.

jquery

2022-09-30 15:59

4 Answers

Array would be better for the first var selector.

 var selector = 'a, form';
vars = selector.split(', ');
$.each(ss, function(i,d){
    $(document).on('click submit',d,function(){
        console.log(123+d);
    });
});
$(document).off('click', 'a');


2022-09-30 15:59

I see some complicated background, but can't I simply disable it and re-register it?

There are many ways to do this, so if this doesn't work, I'll answer with a proper version.

 var selector = 'a, form';

$(document).on('click submit', selector, function(){});
$(document).off('click submit', selector, function(){});

$(document).on('click', 'a', function(){
  alert('click');
  // click process
});
$(document).on('submit', 'form', function(){
  alert('submit');
  // do submit process
});


2022-09-30 15:59

I'm not sure about the intention, but I think we can divide the event type and target into cases.

$(document).on('click submit', selector, function(e){
  if(e.type==='click'&&e.target===$('a').get(0)){
    // click
  } else if(e.type==='submit'&e.target===$('form').get(0)){
    // form submit
  }
});


2022-09-30 15:59

Why don't you look at this.nodeName in the callback of .on and decide what to do?


2022-09-30 15:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.