Jquery在实时预览中是否为空循环

Fab*_*cco 6 javascript jquery loops

我正在使用实时预览脚本.但是现在我希望只有在表单字段中有输入时才会显示电话和传真字段.但我想空语句必须存在问题.有没有人有想法解决这个问题?非常感谢你!

$(document).ready(function() {
  updatePreview();

  $('#live-preview-form input, #live-preview-form textarea #live-preview-form select').bind('blur keyup',updatePreview);
});

function updatePreview(){
  var   contact             = $('#lp-contact'),
        company_name    = $('#lp-company_name'),
        company_extra   = $('#lp-company_extra'),
        adress          = $('#lp-adress'),
        country_code    = $('#lp-country_code'),        
        zip                 = $('#lp-zip'),     
        city            = $('#lp-city'),        
        phone           = $('#lp-phone'),
        fax                 = $('#lp-fax'),
        url                 = $('#lp-url'),
        mail            = $('#lp-mail');


        contact.text($('#contact').val());
        company_name.text($('#company_name').val());
        company_name.html($('#lp-company_name').html().replace(/\n/g,'<br />'));
        company_extra.text($('#company_extra').val());
        adress.text($('#adress').val());
        country_code.text($('#country_code').val() + '-' );
        zip.text($('#zip').val());
        city.text($('#city').val());
        if(! $('#phone')){phone.text('T ' + $('#phone').val())};
        if(! $('#fax')){fax.text('F ' + $('#fax').val())};
        url.text($('#url').val());
        mail.text($('#mail').val());
}
Run Code Online (Sandbox Code Playgroud)

JS小提琴

JS小提琴更新#1

经过大量的尝试和研究后,我想,也许它适用于这段代码:但事实并非如此.

 if (phone.text($('#phone').val().length) != 0){
        phone.text('T ' + $('#phone').val());
    };
Run Code Online (Sandbox Code Playgroud)

dfs*_*fsq 6

这个条件:

if (!$('#phone')) {
    phone.text('T ' + $('#phone').val())
};
Run Code Online (Sandbox Code Playgroud)

应该

if (!$('#phone').length) {
    phone.text('T ' + $('#phone').val())
};
Run Code Online (Sandbox Code Playgroud)

问题是这$('#phone')是一个jQuery实例对象,它始终是一个真正的价值.此对象是HTML元素的类似数组的集合.因此,检查元素是否在页面上的正确方法是检查此集合的长度.基本上,它可以通过这个简单的片段演示:

if ({length: 0}) {
    alert('One');
}

if ({length: 0}.length) {
    alert('Two');
} 
Run Code Online (Sandbox Code Playgroud)