我想发送 2 个变量(im 使用 php 创建一个 html 元素),当用户单击时,会弹出包含 2 个变量的警报。我已经设置了这个:
.PHP:
$item = array (
'string' => $node->getElementsByTagName('string1')->item(0)->nodeValue,
'string2' => $node->getElementsByTagName('string2')->item(0)->nodeValue,
);
$string1 = str_replace(' & ', ' & ', $item['string']);
$string2 = str_replace(' & ', ' & ', $item['string2']);
<a href="#" onclick="doSomething($string1, $string2)" id="'.$title.'" return false;" title="'.$title.'">'.$title.'</a></strong><br />';
Javascript:
<script>
function doSomething(variable1,variable2) {
var myVar1 = variable1;
var myVar2 = variable2;
alert (myVar1+ ' ' +myVar2);
return false;
}
</script>
我试过这个,但是当我单击链接时没有任何反应。
将变量从 php 发送到 javascript 的正确方法是什么?
谢谢你的时间。可以这样做吗?
<a href="#" onclick"doSomething(this) id="'.string1.'" description="'.string2.'" />link </a>
并这样做而不是其他解决方案?
<script>
function doSomething(obj) {
if(obj!= null)
alert ('Obj is Null');
}else {
alert (obj.getAttributeById("id")+' '+obj.getAttributeById("description"));
return false;
}
</script>
您没有在 onclick 中引用参数,因此您的代码如下所示:
<a href="#" onclick="doSomething(Hello, World!)" ...
将变量的内容转换为未定义的变量和语法错误("不括号"?
尝试
<a href="#" onclick="doSomething('$title', '$string')" id= etc...
相反。。请注意变量周围的引号。另请注意,您永远不应该像这样直接将PHP数据转储到Javascript上下文中。正如你所发现的,最轻微的故障,你已经引入了一个JS语法错误,它杀死了整个javascript块。
始终输出 json_encode() 数据,确保您生成语法有效的 JS 代码。
你只需要将这些值连接到你的回显字符串中:
echo '<a href="#" onclick="doSomething(''' . $title . ''', ''' . $string . ''')" id="' . $title . '" return false;" title="' . $title . '">' . $title . '</a></strong><br />';
当你打印php变量时,它只打印变量,所以如果$title等于你好,Java脚本解释器认为Java脚本中有一个名为Hello的变量。为了避免这种情况,您必须将引号内的变量值打印到 HTML 中。
$string = 'World!';
$title = 'Hello';
echo '<a href="#" onclick="doSomething(''' . $title . ''', ''' . $string ''')" id="'.$title.'" return false;" title="'.$title.'">'.$title.'</a></strong><br />';