我想知道如何获取给定 div 中的文本,以及输入的值作为文本。
<div id="example">This is a <input type="text" value="right"/> test.</div>
如果我只是尝试使用 jQuery 获取这样的文本:
$("#example").text();
结果将是 This is a test.
我想要:This is a right test.
输入的数量是未知的。以及元素的顺序...
编辑: 我终于解决了自己的问题:
var finalText="";
$("#example").contents().filter(function() {
if(this.nodeType==3){ finalText =finalText+ this.nodeValue;}
else if(this.nodeName=="INPUT"){ finalText=finalText+this.value;}
return finalText
})
但是@Jonathan Lonowski answer比我的更清晰、更简单!
最佳答案
这是一个可以为您完成此操作的快速插件:
$(document).ready(function() {
$.fn.extend({
getContentText: function() {
var t = '';
this.contents().each(function(i,c) {
var method = $(c).is("input") ? "val" : "text";
t += $(c)[method]();
});
return t;
}
});
alert($("#example").getContentText());
});
在这里试试看: http://jsfiddle.net/wQpHM/
关于javascript - 如何使用它的输入值获取 div 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7826685/