问题
I have a HTML structure like this :
<div class="page" data-page-number="29" data-page-label="18" data-loaded="true" style="width: 816px; height: 1056px;">
<div class="canvasWrapper" style="width: 816px; height: 1056px;">
<canvas id="page29" width="1632" height="2112" style="width: 816px; height: 1056px;"></canvas>
</div>
<div class="textLayer" style="width: 816px; height: 1056px;">
some content
</div>
</div>
<div class="page" data-page-number="29" data-page-label="18" data-loaded="true" style="width: 816px; height: 1056px;">
<div class="canvasWrapper" style="width: 816px; height: 1056px;">
<canvas id="page29" width="1632" height="2112" style="width: 816px; height: 1056px;"></canvas>
</div>
<div class="textLayer" style="width: 816px; height: 1056px;">
some content
</div>
</div>
I want to know that when I click on any textLayer
class, I will get data-page-number="x"
attribute from its parent .page div
.
Only javascript solution required here.
This is basically PDF.js structure.
回答1:
You could use parentNode.dataset to retrieve data attribute of parent node.
var textLayer = document.querySelector('.textLayer');
textLayer.addEventListener('click', function(e) {
console.log('page number: ' + e.target.parentNode.dataset.pageNumber);
console.log('label: ' + e.target.parentNode.dataset.pageLabel);
console.log('loaded: ' + e.target.parentNode.dataset.loaded);
});
<div class="page" data-page-number="29" data-page-label="18" data-loaded="true" style="width: 816px; height: 1056px;">
<div class="canvasWrapper" style="width: 816px; height: 1056px;">
<canvas id="page29" width="1632" height="2112" style="width: 816px; height: 1056px;"></canvas>
</div>
<div class="textLayer" style="width: 816px; height: 1056px;">
some content
</div>
</div>
回答2:
$(".textLayer").on("click",function() {
$(this).parent().attr("data-page-number");
});
pure js:
var classname = document.getElementsByClassName("textLayer");
var myFunction = function() {
var attribute = this.parentElement.getAttribute("data-page-number");
};
for (var i = 0; i < classname.length; i++) {
classname[i].addEventListener('click', myFunction, false);
}
// even shorter version
var elems = document.getElementsByClassName("textLayer").forEach(function(element){
element.addEventListener('click', function(){
var attribute = this.parentElement.getAttribute("data-page-number");
}, false);
});
来源:https://stackoverflow.com/questions/44961886/how-to-get-parent-div-data-attribute-javascript