为了正确分离表示(HTML)和行为(JS),我们不会将任何JS包含到HTML标记中。我们也不会创建标签的类型和JS功能之间的依赖关系,以便我们的代码会
<div align="left">
<a href="" data-id="<?php echo $item->id; ?>" class="tablchet">
<span><?php echo $item->name; ?></span>
</a>
</div>
甚至以下
<div align="left">
<span data-id="<?php echo $item->id; ?>" class="tablchet"><?php echo $item->name; ?></span>
</div>
对于演示文稿,它的确定。现在,使用一些JS插入到单独的文件中,然后将演示文稿HTML与<script src="behavior.js"></script>
或直接导入到<script></script>
之间的HTML文档中。
的JS可能如下:
// Create a function allow you to manipulate the item clicked and the item targeted (with the id).
var showDesc = function (sender, target) {
// When the sender is clicked...
sender.addEventListener("click", function (e) {
e.preventDefault();
// Do Something with the target...
console.log(target);
});
};
// This part will be executed when all HTML presentation from server will be parse.
document.addEventListener("load", function() {
// Our sender is our `class="tablchet"` markup.
var sender = document.getElementsByClassName("tablchet")[0],
// create the id name with the `data-id` information.
id = "d_" + sender.getAttribute("data-id"),
// and our target is finded with its id.
target = document.getElementById(id);
// Use our showDesc with sender and target wished.
showDesc(sender, target);
});
'我试过很多方法,但他们没有working' - 再尝试一些不同的人 –
我假设当你说“自动”你想让它在页面加载时运行。您是否尝试过从jQuery中查看文档的加载事件,或者更好的$(document).ready()? –
除非你已经在使用jQuery,否则使用它来完成这个简单的任务是过度的。如果您希望每次都运行它,只需将它放在页面头部的脚本标记中即可。如果您不希望它在页面加载之前运行,请按照@ jeffcarey的建议并将其附加到文档的加载事件处理程序。 – blm