的jQuery
$(".textAreaContainer").live('click','div', function(){
var divID = this.id;
if ( divID !== "" ){
var lastChar = divID.substr(divID.length - 1);
var t = $('#' + divID ).find(':input');
alert(t.attr('id'));
t = t.clone(false);
t.attr('data-related-field-id', t.attr('id'));
t.attr('id', t.attr('id') + '_Add');
t.attr('data-add-field', 'true');
var text = document.getElementById(divID).innerHTML;
//var textboxId = $('div.textAreaContainer').find('input[type="textArea"]')[lastChar].id;
$('div#placeholder input[type="button"]').hide();
var text = "<p>Please fill out what " + t.attr('id') +" Textarea shall contain</p>";
if ( $('#' + t.attr('id')).length == 0 ) {
$('div#placeholder').html(t);
$('div#placeholder').prepend(text);
}
}
else{
}
});
t.attr('id')应该返回textbox1(或者类似的),而只是返回undefined。
我试过.find(':textarea'),. find('textarea'),. find(text,textArea),. find(':input')以及我通过google找到的其他一些但他们都返回未定义,我不明白为什么。可以在此处找到演示http://jsfiddle.net/xYwaw/。非常感谢任何帮助人员,非常感谢。
编辑:下面是我正在使用的一个非常类似的例子的代码。这就是我想做的事情,但是使用文本框而不是textareas。
$('#textAdd').live('click',function() {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Textbox " + textBoxCounter + " <br><div id='container" + counter + "' class='container'><li><input type='text' id='textBox" + textBoxCounter +"' name='textBox" + textBoxCounter + "'></li></div></br>";
document.getElementById("identifier").appendChild(newdiv);
textBoxCounter++
counter++;
});
$(".container").live('click','div', function(){
var divID = this.id;
if ( divID !== "" ){
var lastChar = divID.substr(divID.length - 1);
var t = $('#' + divID).find('input');
alert(divID);
t = t.clone(false);
t.attr('data-related-field-id', t.attr('id'));
alert(t.attr('id'));
t.attr('id', t.attr('id') + '_Add');
t.attr('data-add-field', 'true');
var text = document.getElementById(divID).innerHTML;
// var textboxId = $('div.container').find('input[type="text"]')[lastChar].id;
$('div#placeholder input[type="button"]').hide();
var text = "<p>Please fill out what " + t.attr('id') +" textbox shall contain</p>";
if ( $('#' + t.attr('id')).length == 0 ) {
$('div#placeholder').html(t);
$('div#placeholder').prepend(text);
}
}
else{
}
});
答案 0 :(得分:1)
首先从第一行删除第二个参数&#39; div&#39;,
$(".textAreaContainer").live('click','div', function(){
......做到了:
$(".textAreaContainer").live('click', function(){
然后改变:
var t = $('#' + divID ).find(':input');
...为:
var t = $(this).find(':input');
因为您已经知道this
是容器所以不需要再次通过ID选择它。此外,您分配给textarea容器的id属性中也包含空格,这是无效的,导致您的原始代码尝试选择'#textAreaContainer 0'
实际上查找0
的元素}标记是#textAreaContainer
的后代。因此,修复创建元素以删除id中的空间的代码一般都是一个好主意,也是解决此问题的另一种方法。