简体   繁体   English

jQuery设置值属性时的奇怪行为

[英]jquery strange behavior when setting the value attribute

I am a little baffled by this issue I encountered. 我对遇到的这个问题感到困惑。

I have an <input type="text" /> element in a template that I am cloning when creating object items. 创建对象项时要克隆的模板中有一个<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(); 
}

However, the value property is not being set. 但是,未设置value属性。 Looking at the rendered html reveals: 查看呈现的html会发现:

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

I have tried a few things (commented out in the above code) but all return empty string, or no value. 我尝试了一些事情(在上面的代码中注释了),但是都返回了空字符串,或者没有值。

Initially I thought that I may be clearing all input fields (for what ever strange reason), but this is not the case. 最初,我认为我可能会清除所有输入字段(出于某种奇怪的原因),但事实并非如此。

my item.Value is not null or undefined. 我的item.Value不是null或未定义。

Has anybody else encountered this issue? 还有其他人遇到过这个问题吗?

Appreciate all input! 感谢所有输入!

don't use .attr() to set the value use .val() 不要使用.attr()设置值,请使用.val()

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

Ex: 例如:

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
}

尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM