[英]How do I get text/html between consecutive <input>s?
由於輸入標簽不應該有結束標簽,是否有一種簡單的方法可以在一系列輸入標簽之間提取文本/ HTML? 例如,對於下面的內容,我想<b>Bob and Tim</b><br>Tim <i>after</i> Bob<br>
檢索<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>
我可以得到文本框的值,但我如何完成上述操作?
通過輕微的標記更改,您可以輕松完成
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());
});
});
已經或多或少地提供了小提琴,並在評論中說明。 但是這里還有其他代碼直接用一個小的解釋:
$("#mybutton").click( function() {
var tempContainer = $("#inputs").clone();
tempContainer.find("input").remove();
alert(tempContainer[0].innerHTML);
});
通過這種方式克隆容器,然后從克隆容器中刪除輸入...最后我們有一個沒有輸入的innerHTML
$("#mybutton").click( function() {
var x = $('div#inputs :not(:input)');
$.each(x, function() {
console.log(this.innerHTML);
});
});
UPDATE
$("#mybutton").click( function() {
var x = $('div#inputs :not(:input)').filter(function() {
return this.toString();
});
console.log(x); // x is the array of DOM Object
});
不確定這是否合適,但你可以像這樣刪除文本:
alert ( $('#inputs').unwrap().text() );
這也會刪除<b></b>
和其他標簽。
理想情況下,如果信息鏈接到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());
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.