由于输入标签不应该有结束标签,是否有一种简单的方法可以在一系列输入标签之间提取文本/ HTML?例如,对于下面我想要检索<b>Bob and Tim</b><br>Tim <i>after</i> Bob<br>
。
<div id="inputs">
<input type="text" value="bob" size="4" />
<b>Bob and Tim</b><br>
<input type="text" value="tim" size="4" />
Tim <i>after</i> Bob<br>
<input type="button" value="get textbox values" id="mybutton" />
</div>
我可以获取文本框的值,但是如何完成上述操作?
答案 0 :(得分:4)
通过轻微的标记更改,您可以轻松完成,
HTML:
<div id="inputs">
<input type="text" value="bob" id="bob" size="4" />
<label for="bob"><b>Bob and Tim</b><br></label>
<input type="text" value="tim" id="tim" size="4" />
<label for="tim">Tim <i>after</i> Bob<br></label>
<input type="button" value="get textbox values" id="mybutton" />
</div>
JS:
$("#mybutton").click( function() {
$.each($('input[type="text"]'), function() {
alert($('label[for=' + this.id + ']').text());
});
});
如果您不喜欢label
标签,请填写,然后将内容简单地包裹在下面的范围内,
<div id="inputs">
<input type="text" value="bob" id="bob" size="4" />
<span><b>Bob and Tim</b><br></span>
<input type="text" value="tim" id="tim" size="4" />
<span>Tim <i>after</i> Bob<br></span>
<input type="button" value="get textbox values" id="mybutton" />
</div>
在JS中,
$("#mybutton").click( function() {
$.each($('input[type="text"]'), function() {
alert($(this).next().text());
});
});
答案 1 :(得分:2)
已经或多或少地提供了小提琴,并在评论中说明。但这里还有其他代码直接用一个小解释:
$("#mybutton").click( function() {
var tempContainer = $("#inputs").clone();
tempContainer.find("input").remove();
alert(tempContainer[0].innerHTML);
});
这样克隆容器,然后从克隆容器中删除输入...最后我们有一个没有输入的innerHTML
答案 2 :(得分:1)
$("#mybutton").click( function() {
var x = $('div#inputs :not(:input)');
$.each(x, function() {
console.log(this.innerHTML);
});
});
<强>更新强>
$("#mybutton").click( function() {
var x = $('div#inputs :not(:input)').filter(function() {
return this.toString();
});
console.log(x); // x is the array of DOM Object
});
答案 3 :(得分:1)
不确定这是否合适,但您可以删除如下文字:
alert ( $('#inputs').unwrap().text() );
这也会删除您的<b></b>
和其他代码。
答案 4 :(得分:0)
理想情况下,如果信息链接到input元素,则应使用<label for="">
。然后,您可以轻松访问相关的值:
<div id="inputs">
<input id="input1" type="text" value="bob" size="4" />
<label for="input1"><b>Bob and Tim</b><br></label>
<input id="input2" type="text" value="tim" size="4" />
<label for="input2 ">Tim <i>after</i> Bob<br></label>
<input type="button" value="get textbox values" id="mybutton" />
</div>
或者:
$("#mybutton").click( function() {
$.each($('input[type="text"]'), function() {
alert($(this).next('label').text());
});
});
或者:
$("#mybutton").click( function() {
$.each($('input[type="text"]'), function() {
alert($('label[for='+this.id+']').text());
});
});