[英]how to access added elements by php from 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:
我正在为过滤的搜索创建动态列表,问题是我尝试使用php添加元素,并且希望它们更改onclick的可见性,为此,我使用功能齐全的css代码,但问题出在javascript,告诉我:
script.js:4 Uncaught TypeError: Cannot read property 'classList' of null at visibilityToggle (script.js:4) at HTMLDivElement.onclick (afficherDept.php:4)
script.js:4未被捕获的TypeError:无法在HTMLDivElement.onclick(afficherDept.php:4)的visibleToggle(script.js:4)处读取null属性'classList'
js_Code: 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 这是添加元素的php代码:--- $ sectionID由循环控制
echo '<div onclick="visibilityToggle('.$sectionID.');"id='.$id.'>'.'ID
'.$dept["id"].'. NOM:'. $dept["nom"].'.CHEF:'.$dept["chef"].'</div>';
echo '<section class="hidden" id=' . $sectionID . '>';
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... 用一个元素的
onclick
调用一个函数,然后使用document.getElementById
再次搜索相同的元素是没有意义的...
Instead I would add a class to your divs in PHP, and use javascript to add a click handler. 相反,我会在PHP中为您的div添加一个类,并使用javascript添加点击处理程序。 This way you know who called the handler and you can toggle the CSS class directly.
这样,您就知道是谁调用了处理程序,并且可以直接切换CSS类。 (note: haven't tested this but I hope the idea is clear)
(注意:尚未测试过,但我希望这个想法很明确)
PHP 的PHP
echo '<div class="clickablediv">simple example</div>';
JAVASCRIPT JAVASCRIPT
let clickableDivs = document.getElementsByClassname("clickablediv")
for(let d of clickableDivs){
d.addEventListener("click", visibilityToggle)
}
function visibilityToggle(e) {
e.target.classList().toggle("showen");
}
The cause for the denoted error is the wrongful rendering of the html markup from your php code. 表示错误的原因是从您的php代码错误渲染了html标记。
You need to put quotes around the argument passed to the visibilityToggle
function. 您需要在传递给
visibilityToggle
函数的参数前后加上引号。
'<div onclick="visibilityToggle(\''. $sectionID. '\')"'
Next, the classList is a DOMTokenList
object - not a function. 接下来,classList是
DOMTokenList
对象-不是函数。
So, you should access the toggle
property like this: 因此,您应该像这样访问
toggle
属性:
section.classList.toggle("showen");
thanks for all your answers.
I fixed the problem. 我解决了这个问题。 In my js function visibilityToggle, the argument id was a html element not a string.
在我的js函数visibleToggle中,参数id是html元素而不是字符串。 i don't know why but it worke
我不知道为什么,但是有效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.