繁体   English   中英

jQuery function 不在 PHP foreach 循环内执行

[英]jQuery function not executing inside PHP foreach loop

我正在尝试为过滤面板生成多个复选框,该复选框将在检查后会刷新一个考虑特定参数的产品列表。

在 foreach 循环中,我通过从 API 调用的 xml 数据中收集过滤器属性成功地创建了复选框

foreach ($attrib->attributeValues->attributeValue as $attribValue)
{
$attribValue = $attribValue->name;
$attribValueID = $attribValue[@id];

$BODY .= sprintf("<input type=\"checkbox\" name=\"%s\" value=\"%s\" id=\"%s\" checked%s=\"checked\" /> %s ",
$attribClass, $attribValue, $attribValue, $attribValue, $attribValue);

接下来,我正在测试一个基本的 jQuery function 并带有两个简单的警报,以确保这些函数实际上正在被调用

$BODY .= "<script type=\"text/javascript\">";
$BODY .= "alert('Hello world!');";
$BODY .= "$(\"#".$attribValue."\").change(function() {";
$BODY .= "var $input = $(this);";
$BODY .= "alert(\"".$attribValue."\");";
$BODY .= "}).change();</script>";

When I run this on the page, the rendered html source code definitely shows that the jQuery function is being generated (multiple times, one for each checkbox created), but I'm not seeing either of the alerts - the one outside the function,或者里面的那个。 这是我第一次使用 jQuery - 有什么想法吗? 一如既往的感谢!

编辑:对不起,这是为两个复选框生成的 HTML 源代码 - 对于所有存在的复选框,这些都是两位数。

<input type="checkbox" name="Color" value="Black" id="Black" checkedBlack="checked" /> Black <script type="text/javascript">alert('Hello world!');$("#Black").change(function() {var  = $(this);alert("Black");}).change();</script>
<input type="checkbox" name="Color" value="Silver" id="Silver" checkedSilver="checked" /> Silver <script type="text/javascript">alert('Hello world!');$("#Silver").change(function() {var  = $(this);alert("Silver");}).change();</script>

我认为你在这里覆盖$attribValue$attribValue = $attribValue->name; - 您可能应该使用不同的变量来存储该值: $myAttribValue = $attribValue->name;

这是我的更新修复。

$BODY .= "<script type=\"text/javascript\">";
$BODY .= "$(document).ready(function(){";
$BODY .= "alert('Hello world!');";
$BODY .= "$(\"#".$attribValue."\").live('click',function() {";
$BODY .= "var \$input = $(this);";
$BODY .= "alert(\"".$attribValue."\");";
$BODY .= "}).click();});</script>";

你可以在这个小提琴中看到这个 output 的例子

我确实必须写入$(document).ready()并转义 php 中的$input以确保它不会呈现为 php 字符串。 我还将.change()更改为.live('click',.click()

实时部分将确保看到动态加载的复选框。 我只是更喜欢点击事件,如果您愿意,可以将其设置为更改。

干杯!

您不需要在这里使用 jQuery 来过度复杂化。

用这个:

function filterToggle(element){
var elementII = document.getElementById(element)
if(elementII.checked){
alert("Checked");
}
else{
alert("Unchecked");
}
}

然后在您的复选框中添加一个 onclick="filterToggle('%s')"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM