开发者

Using jQuery and standard JavaScript together

开发者 https://www.devze.com 2023-03-17 08:26 出处:网络
I have this line of JavaScript / jQuery that I\'m attempting to use to append an element to the DOM and then attach an eventlistener to.

I have this line of JavaScript / jQuery that I'm attempting to use to append an element to the DOM and then attach an eventlistener to.

$('.faq_answer').prev().append(finalRender.cloneNode(true)).addEventListener("click", function () {toggle(this)}, false); 

I know the appending part works perfectly but adding an event listener is 开发者_运维问答giving me grief.

Is it possible / advisable to use jQuery and normal JavaScript together like this? Or is there something in jQuery that would work better. (Very new to jQuery so bear with me).


If you want to use the native methods, then you need to call them against DOM elements, not jQuery objects

var clone = finalRender.cloneNode(true);
clone.addEventListener("click", function () {toggle(this)}, false);

$('.faq_answer')
      .prev()
      .append( clone );

If you want to use jQuery, then you need to wrap the DOM elements in a jQuery object.

  // Drop your DOM element----v----into a jQuery object
var clone = $( finalRender.cloneNode(true) ).bind("click", function (){
    toggle(this);
});

$('.faq_answer')
      .prev()
      .append( clone );


You could do something like this:

 $('.faq_answer').prev().append(finalRender.cloneNode(true)).click(function () {toggle(this)});

which is pure jquery


I think you're wanting to add your event Listener to the cloned Node - not to the prev() of .faq_answer.

If you're importing jQuery, why not use the .click() method anyway instead of mixing? It's simpler! :)

$('.faq_answer').prev().append(finalRender.cloneNode(true).click(function(){
    toggle(this)
}));


Yes, it's possible to use them "together" because jQuery is JavaScript. However in this case there's really no reason to bind event handlers directly like that if you are using the library. It already knows how to manage event handlers, and doing it outside of its control is probably not a good idea unless you really know what you're doing.


I find questions like this are strange, because jQuery is JavaScript.

Based on this mixing up the code that is just plain JavaScript with jQuery code is fine.

But if there is a simpler way of doing what you want in jQuery then I would say to just use jQuery alone.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号