效率低下的jQuery使用率

时间:2016-03-19 10:37:44

标签: javascript jquery

所以我有这段代码:

$( "#contact_seller .modal-content").addClass('has-error');
$( "#contact_seller span").empty();
$( "#contact_seller textarea" ).focus().after( "<span>Please be more precise about what You want to ask</span>" );

但是Webstorm指出,这是jQuery使用效率低下的问题。就像我读到的那样,我需要ise .find()来缩短代码。所以我很兴奋它需要像这样:

$( "#contact_seller")
            .find('.modal-content').addClass('has-error')
            .find('span').empty()
            .find('textarea').focus().after( "<span>Please be more precise about what You want to ask</span>" );

但是很明显这段代码没有正常工作(我假设find()选择每一个下一个项目,但我希望它只选择父元素。)

如何正确编写此代码?

3 个答案:

答案 0 :(得分:3)

作为end的替代方案,您可以随时...

var container = $("#contact_seller"); 
container.find(".modal-content").addClass("has-error");
container.find("span").empty();
container.find("textarea").focus().after("<span>Please...</span>");

答案 1 :(得分:1)

缺少$( "#contact_seller") .find('.modal-content').addClass('has-error').end() .find('span').empty().end() .find('textarea').focus().after( "<span>Please be more precise about what You want to ask</span>" ); 来电。这应该有效:

class FGSingleton {
    static let sharedInstance = FGSingleton()

    var gameScore: Int = 0

    let path = NSBundle.mainBundle().pathForResource("Data", ofType: "plist")
    //below line is creating issue because of using sharedInstance
    let dict = NSDictionary(contentsOfFile: sharedInstance.path!)

    // METHODS
    private init() {
        print(__FUNCTION__)
    }
    func displayGameScore() {
        print("\(__FUNCTION__) \(self.gameScore)")
    }
    func incrementGameScore(scoreInc: Int) {
        self.gameScore += scoreInc
    }
}

答案 2 :(得分:1)

尝试写下面的内容,

var elem = $( "#contact_seller");
elem.find(".modal-content").addClass('has-error');
elem.find("span").empty();
elem.find("textarea").focus().after( "<span>...</span>" );

您可以使用.end(),但此代码效率更高,因为end()会进行反向查找,这对您的上下文来说是一个额外的负担。