jQuery将文本从<li>拉到隐藏的表单字段</li>

时间:2014-05-08 17:17:30

标签: javascript jquery forms dom syntax

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

<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++;
  });

2 个答案:

答案 0 :(得分:1)

是。你遗失了$。你应该这样做:$('#1').text();

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

你为什么不这样做呢?

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

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

答案 1 :(得分:1)

首先,它是$(&#39;#1&#39;)不是(&#39;#1&#39;)

第二, 对于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 (".").

所以,将$(&#39;#1&#39;)更改为$(&#39;#A1&#39;)或您喜欢的任何其他名字以字母开头。

相关问题