doulei3488 2018-04-07 11:13
浏览 48

如何通过PHP从javascript访问添加的元素

I am working on a small project and it is my first so, I have some difficulties to get over. I am creating a dynamic list for a filtered search and the problem is that I try to add elements with php and I want them to change visibility onclick and for that I use a css code which is fully functional but the problem is with the javascript which tells me:

script.js:4 Uncaught TypeError: Cannot read property 'classList' of null at visibilityToggle (script.js:4) at HTMLDivElement.onclick (afficherDept.php:4)

js_Code:

function visibilityToggle(id) {
    var section = document.getElementById(id);
    section.classList().toggle("showen");
}

and this is the php code for adding elements: ---$sectionID is controlled by a loop

echo '<div onclick="visibilityToggle('.$sectionID.');"id='.$id.'>'.'ID 
     '.$dept["id"].'. NOM:'. $dept["nom"].'.CHEF:'.$dept["chef"].'</div>';

echo '<section class="hidden" id=' . $sectionID . '>';

result in HTML

  • 写回答

3条回答 默认 最新

  • doupu3211 2018-04-07 11:48
    关注

    It makes no sense to call a function with onclick from an element, and then use document.getElementById to search for the same element again...

    Instead I would add a class to your divs in PHP, and use javascript to add a click handler. This way you know who called the handler and you can toggle the CSS class directly. (note: haven't tested this but I hope the idea is clear)

    PHP

    echo '<div class="clickablediv">simple example</div>';
    

    JAVASCRIPT

    let clickableDivs = document.getElementsByClassname("clickablediv")
    for(let d of clickableDivs){
        d.addEventListener("click", visibilityToggle)
    }
    function visibilityToggle(e) {
        e.target.classList().toggle("showen");
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分