如何获取父div数据属性javascript

时间:2017-07-07 03:01:46

标签: javascript pdf.js

我有这样的HTML结构:

<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>

我想知道,当我点击任何textLayer课程时,我会从其父data-page-number="x"获得.page div属性。

此处仅需要javascript解决方案。

这基本上是PDF.js结构。

2 个答案:

答案 0 :(得分:2)

您可以使用 parentNode.dataset 来检索父节点的数据属性。

&#13;
&#13;
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);
});
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

$(".textLayer").on("click",function() {
   $(this).parent().attr("data-page-number");
});

纯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);
}

//甚至更短的版本

var elems = document.getElementsByClassName("textLayer").forEach(function(element){ 
    element.addEventListener('click', function(){
        var attribute = this.parentElement.getAttribute("data-page-number");
    }, false);
});