我有一个如下字符串。
<div data-sentence="1"><p>authorised representative (No. 45678) of</p></div>
<div data-sentence="2"><p>you have asked for my advice</p></div>
当用户选择(绘制)像'45678'这样的字符串时,我可以通过下面的函数funGetSelectTxt获取所选文本。我的问题是如何获得这个元素的父div并返回属性'data-sentence'的值?
function funGetSelectTxt() {
var element = '';
if (document.selection) {
element = document.selection.createRange().text;
} else {
element = document.getSelection();
}
return $.trim(element.toString());
}
谢谢,
答案 0 :(得分:2)
试试这个$(this).parent('div').attr('data-sentence')
$('div p').on('mouseup', funGetSelectTxt);
function funGetSelectTxt() {
var element = '';
if (document.selection) {
element = document.selection.createRange().text;
} else {
element = document.getSelection();
}
console.log(element.toString()) //its showing the selected text
console.log($(this).parent('div').attr('data-sentence')) //its get the attr value of parent
// return $.trim(element.toString());
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-sentence="1"><p>authorised representative (No. 45678) of</p></div>
<div data-sentence="2"><p>you have asked for my advice</p></div>
&#13;
答案 1 :(得分:0)
$(div).parent().attr('data-sentence');
答案 2 :(得分:0)
使用jQuery $(element).parent().attr('data-sentence');
在javascript中
var child = document.getElementById("child");
var parent = child.parentNode;
var attr = parent.getAttribute("data-sentence");
答案 3 :(得分:0)
我不确定为什么每个人仍然非常依赖jQuery,因为一些简单的任务甚至不容易编写。
所以在普通的javaScript中,答案是:
element.parentNode.getAttribute('itemprop')
答案 4 :(得分:0)
<div data-sentence="1"><p>authorised representative (No. 45678) of</p></div>
<div data-sentence="2"><p>you have asked for my advice</p></div>
$('div p').on('click',function(){
console.log($(this).parent().attr('data-sentence'));
});
工作链接