我不知道JS的位置可能会改变我的html页面的结果直到今天。我希望图像src在两个不同的URL“点击”之间切换。为什么这个第一个代码的工作方式与我想要的一样,但第二个代码却没有?第二个代码的源html为var not_a_bad_word生成一个空字符串。
第一个代码:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>'Murica!'</title>
</head>
<body>
<?php
$dbhost = 'databasePlace';
$dbname = 'mine';
$dbuser = 'me';
$dbpass = '*****';
$link = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
mysqli_select_db($link, $dbname);
$name = $_GET["fname"];
$query = sprintf(
"SELECT image_url, Type
FROM Pokemon c
WHERE c.name = '%s'",
mysqli_real_escape_string($link, $name));
$result = mysqli_fetch_assoc(mysqli_query($link, $query));
echo '<img id="pokemon_card" onclick="changeImage()" height="450"
width="330" src="' . $result['image_url'] . '"/>';
mysqli_close($link);
?>
<script>
function changeImage() {
element = document.getElementById('pokemon_card');
var not_a_bad_word = "<?php echo $result['image_url']; ?>";
if (element.src == "http://dmisasi.files.wordpress.com/2010/12/david-pokemon-card-back.jpg") {
element.src = not_a_bad_word;
}
else {
element.src="http://dmisasi.files.wordpress.com/2010/12/david-pokemon-card-back.jpg";
}
}
</script>
</body>
</html>
第二段代码:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>'Murica!</title>
<script>
function changeImage() {
element = document.getElementById('pokemon_card');
var not_a_bad_word = "<?php echo $result['image_url']; ?>";
if (element.src == "http://dmisasi.files.wordpress.com/2010/12/david-pokemon-card-back.jpg") {
element.src = not_a_bad_word;
}
else {
element.src="http://dmisasi.files.wordpress.com/2010/12/david-pokemon-card-back.jpg";
}
}
</script>
</head>
<body>
<?php
$dbhost = 'databasePlace';
$dbname = 'mine';
$dbuser = 'me';
$dbpass = '*****';
$link = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
mysqli_select_db($link, $dbname);
$name = $_GET["fname"];
$query = sprintf(
"SELECT image_url, Type
FROM Pokemon c
WHERE c.name = '%s'",
mysqli_real_escape_string($link, $name));
$result = mysqli_fetch_assoc(mysqli_query($link, $query));
echo '<img id="pokemon_card" onclick="changeImage()" height="450"
width="330" src="' . $result['image_url'] . '"/>';
mysqli_close($link);
?>
</body>
</html>
答案 0 :(得分:5)
在第一个示例中,创建变量$result['image_url']
的PHP代码在变量回显之前运行。
如果你看第二个产生空白的例子,$result['image_url']
实际上只是在之后才被定义它已被回显。
答案 1 :(得分:1)
那是因为在第二个例子中插入JS代码时,元素'pokemon_card'还没有。因此,选择器未定义,无法在代码中使用。始终建议将使用DOM元素的js代码放在文档的末尾。