gpt4 book ai didi

javascript - 在 JS 上注册按钮点击处理程序的函数

转载 作者:行者123 更新时间:2023-12-03 10:04:50 25 4
gpt4 key购买 nike

我有一个 PHP 变量调用 $id,它可以是 1 或 2,并且我有两个 id 为 #readmore1 和 #readmore2 的按钮。下面用于注册点击处理程序的代码运行良好,但我想重构它。

有没有办法以某种方式将 PHP 变量传递给 JS?

<script>
$(document).ready(function() {
$("#readmore1").click(function() {
if ($("#readmore1").text() == "Show More") {
$("#readmore1").text("Show Less");
}
else {
$("#readmore1").text("Show More");
}
});
$("#readmore2").click(function() {
if ($("#readmore2").text() == "Show More") {
$("#readmore2").text("Show Less");
}
else {
$("#readmore2").text("Show More");
}
});
});
</script>

最佳答案

Is there a way to do it passing somehow the PHP variable to JS?

不是“将值传递给函数”的意思。但是您可以使用 PHP生成 JS 并在此过程中从 PHP 注入(inject)值。

但是,这实际上可能不是最好的解决方案。为什么不给这两个元素赋予相同的类呢?

$(".readmore").click(function() {
if ($(this).text() == "Show More") {
$(this).text("Show Less");
}
else {
$(this).text("Show More");
}
});

jQuery 会将此处理程序绑定(bind)到具有类 readmore 的所有元素。

关于javascript - 在 JS 上注册按钮点击处理程序的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30404217/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com