首页 > 解决方案 > 我将如何访问此属性?

问题描述

我有一个 td 属性,我想从中提取内容。我尝试了以下 jquery,但收到未定义的警报。有人可以解释为什么吗?

<script>
 document.addEventListener("DOMContentLoaded", function () {
        var items = document.querySelectorAll("td:not(:empty)");
        items.forEach(function (elem) {
            elem.addEventListener("click", function () {
                showModal('modal1', 'rotate');
                changeSrc();
            });

        });
    });

function changeSrc(){
        $(".tabs, .tab active, td").on("click", function(){
            var dataId = $(this).attr("data-ticker");
            alert(dataId);
        });
}
</script>

<div class="tabs">
    <ul class="tabs-list">
        <li class="active"><a href="#tab1">Day 1</a></li>
        <li><a href="#tab2">Day 2</a></li>
    </ul>
    <div id="tab1" class="tab active">
        <table>
            <thead>
                <tr>
                    <th><div class="tzh">Time (ET)</div></th>
                    <th>Track I</th>
                    <th>Track II</th>
                    <th>Track III</th>
                    <th>Track IV</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <th>08:00</th>
                    <td data-ticker="about3" colspan="1" rowspan="2" class="pres">Presentation Title<span>8:00 - 9:00</span><span>Presenter</span></td>
                    <td></td>
                    <td></td>
                    <td></td>
                </tr>

是的,桌子的其余部分被切断以保持简单。

标签: javascripthtmljquerycss

解决方案


似乎您只需要嵌套的事件处理程序。但是,您只会在alert单击具有data-ticker属性的元素时获得一个值,因此这可能应该是您用来查找要设置事件的元素的选择器。

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<div class="tabs">
    <ul class="tabs-list">
        <li class="active"><a href="#tab1">Day 1</a></li>
        <li><a href="#tab2">Day 2</a></li>
    </ul>
    <div id="tab1" class="tab active">
        <table>
            <thead>
                <tr>
                    <th><div class="tzh">Time (ET)</div></th>
                    <th>Track I</th>
                    <th>Track II</th>
                    <th>Track III</th>
                    <th>Track IV</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>08:00</td>
                    <td data-ticker="about3" colspan="1" rowspan="2" class="pres">Presentation Title<span>8:00 - 9:00</span><span>Presenter</span></td>
                    <td></td>
                    <td></td>
                    <td></td>
                </tr>
                </table>

<!-- If you place your script at the end of the body, there's no 
     need to set up a DOMContentLoaded event handler because by 
     the time the parser gets here, all the HTML in the body will
     have been parsed into memory.  -->
<script>
  $("[data-ticker]").on("click", function(event){
     alert(this.dataset.ticker);
  });
</script>


推荐阅读