简体   繁体   中英

How can I don't repeat a part of code

I have this code:

$(document)
.on(
  "click", 
  "#target", 
  function() { 
    //SOME_CODE
  }
);

And now I have to bind //SOME_CODE to another event after some specific code that will have to be executed only on this second event:

$(document)
.on(
  "click",
  "#anotherTarget",
  function() {
    //SOME_OTHER_CODE
    //SOME_CODE
  }
);

How can I call //SOME_CODE without copy-and-paste it and without specify a function on top of both events ?

I've tried with this code:

$(document)
.on(
  "click.somecode", 
  "#target", 
  function() { 
    //SOME_CODE
  }
);

$(document)
.on(
  "click",
  "#anotherTarget",
  function() {
    //SOME_OTHER_CODE
    $(document).trigger("click.somecode");
  }
);

But the //SOME_CODE is not executed.

try this

$("#target").trigger('click')

see fiddle demo

Just fire a click event for the target?

$(document)
.on(
  "click",
  "#anotherTarget",
  function() {
    //SOME_OTHER_CODE
    $("#target").click();
  }
);

Put //SOME_CODE in a function, and call it. Example:

function doSomeCode() {
 //SOME_CODE
}

$(document)
.on(
  "click.somecode", 
  "#target", 
  doSomeCode
);

$(document)
.on(
  "click",
  "#anotherTarget",
  function() {
    //SOME_OTHER_CODE
    doSomeCode();
  }
);

You can try like the following:

     $(document)
      .on(
        "click.somecode", 
        "#target", 
        function() { 
          console.log("SOME_CODE");
        }
      );

      $(document)
      .on(
        "click",
        "#anotherTarget",
        function() {
          console.log("SOME_OTHER_CODE");
          $("#target").trigger("click");
        }
      );

See the fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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