Javascript 如何使用jquery选择具有“abbr”属性特定值的元素
我的html的一部分是:Javascript 如何使用jquery选择具有“abbr”属性特定值的元素,javascript,jquery,jquery-selectors,abbr,Javascript,Jquery,Jquery Selectors,Abbr,我的html的一部分是: <tr id="row"> <td abbr='selectme'> <div>Texti inside the div</div> Text outside the div </td> <td> any others I dont care about <td> </tr> 但是它不返回任何内容。还返回子元素的文本内容,并将其过滤
<tr id="row">
<td abbr='selectme'>
<div>Texti inside the div</div>
Text outside the div
</td>
<td>
any others I dont care about
<td>
</tr>
但是它不返回任何内容。还返回子元素的文本内容,并将其过滤掉
var text = $("#row").find("[abbr='selectme']").contents().filter(function () {
//select only text nodes of the targetted td element
return this.nodeType == 3
}).text();
演示:
返回子元素的文本内容,并将其过滤掉
var text = $("#row").find("[abbr='selectme']").contents().filter(function () {
//select only text nodes of the targetted td element
return this.nodeType == 3
}).text();
演示:
你得不到任何回报的原因可能是因为你必须把它包装在一个盒子里
$( document ).ready(function() {}); or $(function(){});
因为在通过jquery访问div之前,需要在DOM中加载div,否则您将访问一个尚未加载的元素。因此,通过使用此代码:
$(function () {
alert($("#row").find("[abbr='selectme']").text());
});
您将获得以下文本:
文本在div中
div外的文本
现在,由于您只想获取div之外的文本,而div是纯文本,不包含任何标记,因此必须使用.contetns.filter函数并获取
nodeType === 3
数值3用于获取文本节点。最后的代码是这样的,我用alert来说明
// 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之外的输出文本
这是一个有效的例子,你没有得到任何回报的原因可能是因为你必须用一个
$( document ).ready(function() {}); or $(function(){});
因为在通过jquery访问div之前,需要在DOM中加载div,否则您将访问一个尚未加载的元素。因此,通过使用此代码:
$(function () {
alert($("#row").find("[abbr='selectme']").text());
});
您将获得以下文本:
文本在div中
div外的文本
现在,由于您只想获取div之外的文本,而div是纯文本,不包含任何标记,因此必须使用.contetns.filter函数并获取
nodeType === 3
数值3用于获取文本节点。最后的代码是这样的,我用alert来说明
// 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之外的输出文本
以下是工作示例您只需按属性名称搜索元素即可:
$("[abbr='selectme']").text();
您只需按属性名称搜索元素:
$("[abbr='selectme']").text();
请考虑使用ValIDHTML,例如,使用数据-*属性。可以肯定的是,ID为row的元素是唯一的吗?如果您有一个表和有效的标记,那么它就可以正常工作……但它不会返回任何内容。不,它返回DIV中的所有文本:检查常见的疑义:脚本运行得太快,不在就绪而不在页面结束,超过一个ID行的元素,等等,请考虑使用ValIDHTML,例如,使用DATAB-*属性。可以肯定的是,ID为row的元素是唯一的吗?如果您有一个表和有效的标记,那么它就可以正常工作……但它不会返回任何内容。不,它不会,它会返回div中的所有文本:检查常见的疑点:脚本运行过快未在内部就绪且未在页面末尾,多个id行元素,等等+1,对于详细解释,它对像我这样的初学者有帮助+1,对于详细解释,它对像我这样的初学者有帮助