Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
86 views
in Technique[技术] by (71.8m points)

javascript element like in jquery? How do I get with the "these" variable

this jquery code

    $(".entry-content").click(function(){
        console.log(this); // "this" <div class="entry-content"></div>
        alert("aasasd");
    });

I tried it myself to reach this parameter when using javascript. I can get it as a parameter from the callback function, but I couldn't get it like this.

function $( element ) {
        element = document.querySelectorAll(element);
        this.click = ( callback ) => {
            for (let i = 0; i < element.length; i++) {
                element[i].addEventListener("click", function() {
                    callback( element[i] );
                });
            }
        }
        return this;
    }
    
    $(".entry-content").click(function(element){
        console.log(element); // The "element" is being sent from the callback () function.
        alert("aasasd");
    });

So instead, how do I access "this" as in jquery

question from:https://stackoverflow.com/questions/65861951/javascript-element-like-in-jquery-how-do-i-get-with-the-these-variable

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use .bind when assigning the listener to set a this value. With jQuery, this is just the element, or element[i].

Since you don't care about the indicies, only the elements, you could also consider iterating over the elements directly:

function $(selector) {
  const elements = document.querySelectorAll(selector);
  return {
    click(callback) {
      for (const element of elements) {
        element.addEventListener('click', callback.bind(element));
      }
    }
  };
}
$(".entry-content").click(function() {
  console.log(this);
});
<button class="entry-content">click</button>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...