dskld5423 2014-08-31 23:34
浏览 8
已采纳

使用PHP变量在javascript中设置链接名称

What I am trying to do is load a page, get a PHP variable into JavaScript, and set my element (Link) to said variable. Then, when you click on the link, I would like it to change from open or close to close or open. For some reason, the other solutions I have looked at don't seem to work. What seems to be the issue with the following code? I'm slightly confused as to why this isn't working.

<script type="text/javascript">
var state =  "<?php echo $var; ?>";
document.getElementById('open').text = state;
function toggleText(button_id) 
{
   if (document.getElementById('button_id').text == "Open") 
   {
       document.getElementById('button_id').text = "Close";
   }
   else 
   {
     document.getElementById('button_id').text = "Open";
   }
}
</script>
<a id="open" onclick="toggleText('open')" href="#"></a>

Thanks a lot, this is the last leg of my project, and for some reason whatever I try wont make it work.

Notice: I have also tried instead of .text .innerHTML and it also did not work.

  • 写回答

4条回答 默认 最新

  • dtr53557 2014-08-31 23:42
    关注
    <script type="text/javascript">
    document.getElementById('buttonid').innerHTML = "<?php echo $var; ?>";
    function toggleText(button) 
    {
       if (button.innerHTML == "Open") 
       {
           button.innerHTML = "Close";
       }
       else 
       {
         button.innerHTML = "Open";
       }
    }
    </script>
    <a id="buttonid" onclick="toggleText(this)" href="#"></a>
    

    Put script after </body> tag

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 武汉岩海低应变分析软件,导数据库里不显示波形图
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 CanMv K210开发板实现功能
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题