您没有得到任何回报的原因可能是因为您必须将其包装在一个
$( document ).ready(function() {}); or $(function(){});
因为 div 在通过 jquery 到达之前需要在 DOM 中加载,否则您正在访问尚未加载的元素。因此,通过使用此代码:
$(function () {
alert($("#row").find("[abbr='selectme']").text());
});
您将获得以下文本: div 内的文本 div 外的文本
现在,由于您只想获取文本“div 外的文本”,它是纯文本,没有包含在任何标签中,您必须使用 .contetns().filter() 函数并获取
nodeType === 3
数值“3”用于获取文本节点。所以你的最终代码将如下所示(我使用警报进行说明)
// Shorthand for $( document ).ready()
$(function () {
// getting the specific text and saving into a variable
//getting the contents of the target element
var myText = $("#row").find("[abbr='selectme']").contents()
// using the filter to get the text node
.filter(function () {
return this.nodeType === 3;
//getting the final text
}).text();
alert(myText);
});
现在,当您运行程序时,您将得到输出“div 外的文本”。
这是工作示例http://jsfiddle.net/842nn/