当从下拉菜单中选择特定选项时如何document.write

时间:2014-09-09 09:11:19

标签: javascript jquery html

当我从下拉菜单中选择特定选项时,我尝试执行document.write。

这是我到目前为止所拥有的:

HTML

<select name="active" class="button_select" id="active" style="width:150px" >
<option id="on" value="on">Online</option>
<option id="off" value="" <?php if($rows['active']=='') { echo 'selected'; } elseif ($rows['active']=='on' && $rows['images'] == 0) { echo 'selected'; } ?>>Offline</option>
<option id="arch" value="arch" <?php if($rows['active']=='arch') { echo 'selected'; } ?>>Archived</option>
</select>

的Javascript

<script>        
$("#active").change(function(){
var id = $(this).find("option:selected").attr("id");

switch (id){
case "on":
document.write('<a href="select.php"><img src="../images/icons/coquette/48x48/accept.png" alt="" border="0" /></a>');
break;
}
});             
</script>

我已将Javascript放在HTML上方 - 目前,当选择on选项时,accept.png应出现的位置不会出现任何内容。

有人可以提出解决方案吗?

2 个答案:

答案 0 :(得分:1)

  • 使用$(document).ready
  • 包裹您的代码
  • 您可以使用.replaceWith()代替document.write(仅提及)。

Fiddle

$(document).ready(function()
{
    $("#active").change(function()
    {
        var id = $(this).find("option:selected").attr("id");
        switch(id)
        {
            case "on":
                $(this).replaceWith('<a href="select.php"><img src="../images/icons/coquette/48x48/accept.png" alt="" border="0" /></a>');
                break;
        }
    });
});
$(document).ready期间处理选定的选项

更新

Updated fiddle

$(document).ready(function()
{
    $("#active").change(function()
    {
        handleSelected($(this));
    });

    handleSelected($('#active'));

    function handleSelected(jElement)
    {
        var id = jElement.find("option:selected").attr("id");
        switch(id)
        {
            case "on":
                $("div.wrapper").replaceWith('<a href="select.php"><img src="../images/icons/coquette/48x48/accept.png" alt="" border="0" /></a>');
                break;
        }
    }
});

答案 1 :(得分:0)

以这种方式更改您的代码:

$(document).ready(function()
{
    $("#active").change(function()
    {
        var id = $(this).find("option:selected").attr("id");
        switch(id)
        {
            case "on":
                $("body").append('<a href="select.php"><img src="../images/icons/coquette/48x48/accept.png" alt="" border="0" /></a>');
                break;
        }
    });
});

小提琴:http://jsfiddle.net/praveenscience/g9bm7mko/

相关问题