设置value属性时jquery奇怪的行为

时间:2013-06-20 04:30:51

标签: javascript jquery dom

我对遇到的这个问题感到有些困惑。

我在创建对象项时克隆的模板中有一个<input type="text" />元素。

function buildSectionTest(item) {
if (item == null)
    return;
var sectionItem = $('.templates-mc .templates-mc-section-item').clone();

$('.mc-label', sectionItem).text(item.TestDescription);
$('.mc-input', sectionItem).attr({ 'testid': item.ID, 'syntax': item.TestSyntax, 'value': item.Value });
//$('.mc-input', sectionItem).val("TEST");
//alert($('.mc-input').attr('value');
//alert($('.mc-input').val());

return sectionItem.html(); 
}

但是,未设置value属性。查看渲染的html显示:

<input class="mc-input rounded-corners" type="text" testid="6446" syntax="[input]">

我尝试了一些事情(在上面的代码中注释掉了)但是都返回空字符串,或者没有值。

最初我认为我可能正在清除所有输入字段(出于奇怪的原因),但事实并非如此。

我的item.Value不为null或未定义。

还有其他人遇到过这个问题吗?

感谢所有输入!

2 个答案:

答案 0 :(得分:3)

请勿使用.attr()将值设置为.val()

$('.mc-input', sectionItem).attr({ 'testid': item.ID, 'syntax': item.TestSyntax}).val(item.Value);

例如:

function buildSectionTest(item) {
    if (item == null)
        return;

    var sectionItem = $('.templates-mc .templates-mc-section-item').clone();

    $('.mc-label', sectionItem).text(item.TestDescription);
    $('.mc-input', sectionItem).attr({ 'testid': item.ID, 'syntax': item.TestSyntax}).val(item.Value);
    //$('.mc-input', sectionItem).val("TEST");
    //alert($('.mc-input').attr('value');
    //alert($('.mc-input').val());

    return sectionItem; //do not return the html
}

答案 1 :(得分:-2)

试试这个:

$('.mc-input', sectionItem).attr({ 'testid': item.ID, 'syntax': item.TestSyntax, this.val(item.Value) });