This but not $(this)

落爺英雄遲暮 提交于 2019-12-12 05:52:33

问题


OK so in jQuery;

I have a selecter $("#gmap")

I want to do alot of code in context of my selector. I have always been lazy and used .each() even though there is only one of them.

$("#gmap321654987789").each(function(){
 $(this).....
});

Is this particuarly effitiant? I hate code that doesn't feel 'right'.

Is there a mechanism for say... or something similar.

$("#gmap321654987789").this(function(){
 $(this).....
});

回答1:


Just cache the object and work with it like normal:

var $gmap = $('#gmap321654987789'); // Get your jQuery object
console.log($gmap);
console.log($gmap.text());



回答2:


well if there is only one one them (should be because you are selecting by id) you can just chain methods $("#gmap").val("new").attr('someattr','').etc




回答3:


You could just:

var myElement = $("#gmap321654987789");
myElement....



回答4:


You can also try "with" in JS so you focus on the properties of your object.




回答5:


try this (untested)

(function($){
    $.fn.me = function(func) {
        func.call(this[0]);
        return this;    
    }
})(jQuery);

and use with:

$("#gmap321654987789").me(function(){
    this.innerHTML = 'edited';
}).css('border')....



回答6:


Maybe a function pattern? Perhaps you could cut your implementation down to one or more methods, or even just a single parametrised method.

$.fn.doThingsToAMap = function() {
    $(this).doThis();
    $(this).doThat();
    return this;
};


$("#gmap321654987789").doThingsToAMap();


来源:https://stackoverflow.com/questions/4747716/this-but-not-this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!