我有一个 JS 函数,可以将带有值的键添加到当前 URL。下面有两个几乎相同的链接,唯一的区别是传递给 JS 函数的变量。一个链接传递 $month,另一个链接传递 $event_category。由于某种原因,当传递 $event_category 时,JS 函数甚至没有被调用。有人知道我做错了什么吗?
您必须向右滚动才能看到差异在哪里。
$month = 1;
$event_category = (string) ($eventCategories[$k]["event_category"]);
echo gettype($event_category); // prints "string"
// doesn't work?
echo '<div class="month selected"><a href="javascript:void(0);" onclick="javascript:insertParam('. "'event_category'" .', '. $event_category .');" class="button" role="button">
<image width="100" height="60" src="images/'. $images_list[$eventCategories[$k]["event_category"]].'"></a></div>';
// works
echo '<div class="month selected"><a href="javascript:void(0);" onclick="javascript:insertParam('. "'event_category'" .', '. $month .');" class="button" role="button">
<image width="100" height="60" src="images/'. $images_list[$eventCategories[$k]["event_category"]].'"></a></div>';
最佳答案
您应该在 $event_category 两边加上引号,否则 javascript 会将其解释为变量。所以,转换
. $event_category .
至
. '"' . $event_category . '"' .
关于javascript - 使用特定变量从 PHP echo 调用 JS 函数时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38801473/