jQuery json数据没有格式化

时间:2014-02-12 23:52:50

标签: javascript jquery json jquery-easyui

行。 jQuery绝对不是我的力量。事实上,我总是对jQuery和js都是一个总菜鸟。我正在尝试简单地格式化电话号码并显示它,但我得到的只是没有格式化的原始10位数字。这是代码:

function phoneFormat(phone) {
        phone = phone.replace(/[^0-9]/g, '');
        phone = phone.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
        return phone;
    }
function editUser(){
        var row = $('#dg').datagrid('getSelected');
        if (row){
            $('#dlg').dialog('open').dialog('setTitle','Prospect Details');
            $('#fm').form('load',row);
            url = 'update_user.php?id='+row.id;
            $('#dia_name').html(row.Name);
            var phone = $('#dia_phone').html(row.Phone);
            phone = phoneFormat(phone);
            $('#dia_phone').text(phone);
        }
    }


<div id="dlg" class="easyui-dialog" style="width:500px;height:280px;padding:10px 20px"
        closed="true" buttons="#dlg-buttons">
    <div id="dia_name" class="ftitle">Prospect Name</div>
    <div id="dia_phone" class="rtitle">Prospect Phone</div>
    <form id="fm" method="post" novalidate>
        <div class="fitem">
            <label>Prospect Name:</label>
            <input name="Name" class="easyui-validatebox" required="true">
        </div>
        <div class="fitem">
            <label>Phone:</label>
            <input name="Phone">
        </div>
        <div class="fitem">
            <label>Email:</label>
            <input name="Email" class="easyui-validatebox" validType="email">
        </div>
        <div class="fitem">
            <label>Received Datetime:</label>
            <input name="rcvd_datetime" class="easyui-validatebox" required="true">
        </div>
    </form>
</div>

数据来自一个非常简单的PHP脚本,它肯定会正确地传回数据。我遇到的问题实际上只是电话号码的格式化。该数字来自数据库查询,作为纯10位数字符串,我想将其显示为(555)555-5555格式。

提前感谢您的帮助。我再次对javascript非常新,所以请保持温和。

1 个答案:

答案 0 :(得分:1)

.html仅在您未提供参数时返回数据,请查看.html reference以查看正确的用法

这样:

var phone = $('#dia_phone').html(row.Phone);

不会向phone返回任何内容,因为您正在传递参数 它需要是

var phone = $('#dia_phone').html();

你想要的是:

var phone = phoneFormat(row.Phone);
$("#dia_phone").html(phone);