javascript onchange事件仅在同一页面上运行一次

时间:2013-09-18 18:13:44

标签: javascript time onchange

我有一个表格,用户可以自定义他们从我们网站上购买的标签。当用户从下拉列表中选择该标记时,javascript的目标是将图片更改为我们原始标记数据库中的图片。

当用户购买10个标签时,我会在页面加载时重现代码10次。问题是唯一有效的是第一个。它很棒!第二个(虽然复制和粘贴的代码)根本无法正常工作。如果我将getElementById重命名为标记1.第二个框适用于第一个框。但不正确。

这是一些代码。

生成选择选项的php函数。

function createSelectDT(){


        $qry = "SELECT `products_model`, `products_image` FROM `zen_products` WHERE `products_id` > '0'";
        $result = mysql_query($qry)or die(mysql_error());

        //we actually need the last two digits to find what department its in.

        while ($row = mysql_fetch_assoc($result)){
            $model = $row['products_model'];
            $image = $row['products_image'];

            //how many characters does the string have?
            $length = strlen($model);

            //subtract two so we can start there
            $length = $length - 2 ;

            //get the last to digits!

            $last2 = substr($model, $length, 2);

            //we have the last two lets make sure that they equal dog tags and echo it as a select option

            if ($last2 == "01"){
                echo "<option value=\"images/" . $image . "\">" . $model . "</option>";
            }
        }

    }

html和javascript

<td><img id="tag1" src="images/1.png" /></td><td><select onchange="document.getElementById('tag1').src = this.options[this.selectedIndex].value;" name="tag1"><?php createSelectDT(); ?></select><br />New Header:<input type="text" name="tag1head" /><br />New background:<input type="text" name="tag1bg" /><br />New Footer:<input type="text" name="tag1foot" /><br />Upload image:</td>

<td><img id "tagtwo" src="images/1.png" /></td>     <td><select onchange="document.getElementById('tagtwo').src = this.options[this.selectedIndex].value;" name="tag2"><?php createSelectDT(); ?></select><br />New Header:<input type="text" name="tag1head" /><br />New background:<input type="text" name="tag1bg" /><br />New Footer:<input type="text" name="tag1foot" /><br />Upload image:</td>

有趣的是,如果我将javscript getElementById设置为tag1,tag2将会起作用。但不适用于tag2。这是怎么回事?

2 个答案:

答案 0 :(得分:1)

我尝试了一下你所写内容的略微修改版本,并且它应该按原样运行:

<select name="tag2" onchange="document.getElementById('tagtwo').src = this.value;">
       <option value="tag2.jpg">tag2</option>
       <option value="tag3.jpg">tag3</option>
</select>

您可能应该通过稍微重写来将onchange指向函数:

<script type="text/javascript">

function setImage(elem)
{
    document.getElementById(elem.name).src = elem.value;
    return false;
}

</script>

<select name="tag1" onchange="setImage(this);">
     <option value="tag2.jpg">tag2</option>
     <option value="tag3.jpg">tag3</option>
</select>

要使上述函数起作用,name和id必须相等 - 所以在select name =“tag2”和img id =“tag2”上。如果这不起作用,请发布createSelectDT()的值,因为可能存在问题。

答案 1 :(得分:0)

问题最终成为一个HTML拼写错误。缺少等号。

相关问题