如何使用jQuery来获取父元素的文字? [英] How to get the text of parent element using jquery?

查看:532
本文介绍了如何使用jQuery来获取父元素的文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个div,其中包含一个超链接删除,它的点击数,我想div标签的文本。怎么可能在jQuery的?!

I have a div which contains a delete hyperlink, onlick of it, I want the text of the div tag. How is it possible in jquery?!

<div>sometext<a href="#">delete</a></div>

我想div标签'sometext的文本,如果可能的是,ID div中了。 任何想法?!

I want to get the text of div tag 'sometext' and if possible the id of that div too. Any ideas?!

推荐答案

有这样做的问题:

$(this).parent().text();

时,它会得到所有的分区中的文本(sometext和删除)。

is that it will get ALL the text within the div (sometext AND delete).

我假设你只想在DIV的文字,而不是链接。

I'm assuming you only want the text in the div and not the link.

我敲了一个例子上的jsfiddle:

I've knocked up an example on jsFiddle:

http://jsfiddle.net/HK794/

在理想情况下,你可能需要包装在一个跨度的文字,如:

Ideally you might want to wrap the text in a span, like:

<div id="div1"><span>sometext</span><a href="#">delete</a></div>

那么你的JavaScript将是:

Then your JavaScript would be:

$("a").click(function(e){

    $div = $(this).parent("div");

    id = $div.attr("id");

    text = $div.find("span").text();

    alert( text  );

    e.preventDefault();
});

修改

由于@DarthJDG指出,如果你不想改变你的标记,任何这些也将工作:

As @DarthJDG states if you don't want to change your markup, any these would also work:

text = $div.get(0).childNodes[0].nodeValue;

//OR    
text = $div[0].childNodes[0].nodeValue;

//OR
text = $div.get(0).firstChild.nodeValue;

//OR
text = $div[0].firstChild.nodeValue;

//OR

//Gets the first text node
$div.contents().filter(function() {
    return this.nodeType == Node.TEXT_NODE;
}).text();

这篇关于如何使用jQuery来获取父元素的文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆