【问题标题】:jQuery Pulling text from <li> to hidden form fieldjQuery 将文本从 <li> 拉到隐藏的表单域
【发布时间】:2014-06-26 05:44:48
【问题描述】:

我知道我犯了一些简单的错误,但我似乎看不到它。

<li class="ui-state-default" id="1">Text I want to pull</li>

$('#control1').prop('value', "test" );           //this works
$('#control2').prop('value', ('#1').text() );    //this does not work

//OUTPUT:
<input type="hidden" name="control1" id="control1" value="test">
<input type="hidden" name="control1" id="control1" value="">

我正在使用 $(document).ready(function() { //code });

我正在用 jQuery 填充列表项的 ID 字段(有 8 个列表项):

//this code works fine the DOM updates and I have numbered list items id=1...id=4...id=8
var controlnumber = 1;
$( "li" ).each(function() {
  $(this).prop('id', controlnumber);
  controlnumber++;
  });

【问题讨论】:

    标签: javascript jquery forms dom syntax


    【解决方案1】:

    首先,它是 $('#1') 而不是 ('#1')

    第二, 对于 HTML 4

    ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number     of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
    

    因此,将 $('#1') 更改为 $('#A1') 或任何其他您喜欢的以字母开头的名称。

    【讨论】:

    • 谢谢!这是一个漫长的早晨,我知道这真的很简单。
    • 也感谢以字母开头的注释。不知道。
    • 是的,我真的只需要这些“控件”的八个唯一名称,所以我打算添加“a”a1 a2 a3 a4(有一个字母)
    • 不知道给它们起什么名字,我也在循环中所以我使用 var++ 所以最后的数字很好用。
    【解决方案2】:

    是的。你错过了$。你应该这样做:$('#1').text();

    $('#control2').prop('value', $('#1').text() )
                                 ^------------------ add $ here.
    

    你为什么不干脆这样做?

    $('#control2').val($('#1').text());
    

    另外值得注意的是,只有数字 ID 是个坏主意。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多