jQuery切换焦点/模糊的兄弟姐妹

时间:2011-03-07 20:53:25

标签: jquery mobile-website jquery-mobile performance

所以我现在就拥有它并且它可以工作,但是我想知道在编写移动网站时是否有最佳的写作方式,如果有重要的话,还有性能。

想想在元素下滑下(切换)的工具提示,我在页面上也有大约30个工具提示div,因为这将用于多个元素

JS:

$('.mobile-tool-tip').each(function() { 
    $(this).hide();                         
    $(this).prev().focus(function() {
        $(this).next().slideToggle('fast');
    });
    $(this).prev().blur(function() {                    
        $(this).next().slideToggle('fast');
    });
});

HTML for mobile-tool-tip功能

<div data-role="fieldcontain">
    <input type="text" name="telephone" id="telephone" placeholder="Phone Number*" />
    <div class="mobile-tool-tip" id="telephone_tip">Valid format <strong>999-999-9999</strong>. Please include the area code.</div>
</div>

一直在使用这个(感谢Hunter)切换元素,但不能让它与next()一起使用,我不想手工编写每个工具提示div

$("[name=field_name]").change(function() {
    var show = $(this).val();
    $("#hidden_div").toggle(show);
});

3 个答案:

答案 0 :(得分:4)

一些建议:

  • 使用CSS保存几毫秒隐藏.mobile-tool-tip元素。
  • 将事件附加到父div。找到父元素要比找一个兄弟姐妹更快。
  • 如果您正在寻找nextprev元素,并且它是一个特定元素,我总是建议使用`nextAll(“。mobile-tool-tip”)
  • 您正在消耗时间$(this).prev()。不要两次。 jQuery中的许多函数返回对最后一个查询的引用,这使您可以链接调用(类似$(".anElement").hide().remove())。利用它来节省时间。
  • 当您对focusblur进行操作时,请使用确定性方法隐藏/显示或启用/禁用元素。这将确保您不会错过任何活动或特殊场合,并且可以防止任何与之相关的错误。

所以:

$('.mobile-tool-tip').each(function() { 
    $(this).prev().focus(function() {
        $(this).nextAll(".mobile-tool-tip").slideDown('fast');
    }).blur(function() {                    
        $(this).nextAll(".mobile-tool-tip").slideUp('fast');
    });

});

祝你好运!

答案 1 :(得分:1)

一些简单的想法。

  1. 您可以缓存选择器并将调用链接在一起,以避免对dom进行任何迭代。
  2. 你还可以在焦点和模糊函数中创建一个尖端的闭包,这将导致没有额外的dom迭代。
  3. 所以你最终会得到类似的东西......

    $('.mobile-tool-tip').each(function() {
        var $tip = $(this);
        $tip.hide().prev().focus(function() {
            $tip.slideToggle('fast');
        }).blur(function() {                    
            $tip.slideToggle('fast');
        });
    });
    

    jsfiddle在使用闭包触发事件时显示出轻微的性能提升。

答案 2 :(得分:0)

您可以尝试通过使用变量来保存$(this).next()元素,从而将一些调用组合到DOM中。根据文件的大小,这可以减少大量的时间而不必进行两次调用。

var nextElement = $(this).next();
$(this).prev().blur(function(){
$(nextElement).slideToggle();
}
相关问题