jQuery从<灯光>隐藏表单字段

jQuery Pulling text from <li> to hidden form field

本文关键字:隐藏 表单 字段 灯光 jQuery      更新时间:2023-09-26

我知道我犯了一个简单的错误,我就是看不出来。

<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="">

我用$(文档)时(函数(){//代码});

我正在用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++;
  });

首先,这是美元(# 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')或者其他你喜欢的以字母开头的名字

是。你缺少$。你应该这样做:$('#1').text();

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

你为什么不直接这样做呢?

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

值得注意的是,只有数字id是一个坏主意。