在php代码中编写javascript

时间:2014-05-17 14:39:14

标签: javascript php

我知道如何在php脚本中编写此代码:

<a href = "javascript:void(0)" onclick = "document.getElementById('lightpos<?=$the_job_id;?>').style.display='block';document.getElementById('fadepos<?=$the_job_id;?>').style.display='block'"><img src='img/remove.png' onmouseover=this.src='img/remove_light.png' onmouseout=this.src='img/remove.png'></a>

我试过了,但这不起作用:

<?php
  echo" <a href = 'javascript:void(0)' onclick = 'document.getElementById('lightpos<?=$the_job_id;?>').style.display='block';document.getElementById('fadepos<?=$the_job_id;?>').style.display='block' '><img src='img/remove.png' onmouseover=this.src='img/remove_light.png' onmouseout=this.src='img/remove.png'></a> ";
?>

任何想法?

2 个答案:

答案 0 :(得分:3)

答案是“回答大量HTML”,因为您在<?=语句中使用echo而导致代码失败的原因只是echo的简写1}}

所以这样做,

<a href = "javascript:void(0)" onclick = "clicked(<?=$the_job_id;?>, <?=$the_job_id;?>)">
    <img src='img/remove.png' onmouseover="this.src='img/remove_light.png'" onmouseout="this.src='img/remove.png'" />
</a>

<script>
    //If you are sure that lightposid and fadeposid are going to be same
    //than 1 parameter is sufficient
    function clicked(lightposid, fadeposid) {
        document.getElementById('lightpos' + lightposid).style.display='block';
        document.getElementById('fadepos' + fadeposid).style.display='block';
    }
</script>

为了上帝的缘故,请使用:hover伪而不是使用mouseovermouseout事件......

如果您要更换img标记的网址而不是使用函数。

Demo (控制台日志将返回undefined,因为我没有 lightpos1 id元素fadepos1

注意:在上面的演示中,我使用1, 1作为<?=$the_job_id;?>的值。所以他们将是你真正的工作ids ..


如果您愿意删除img代码,请将其替换为span元素,例如

<a href = "javascript:void(0)" onclick = "clicked(<?=$the_job_id;?>, <?=$the_job_id;?>)">
    <span class="remove"></span>
</a>

现在,在CSS中使用类似的内容

.remove {
    display: inline-block;
    height: 30px;
    width: 30px; /* Set height and width according to your requirements */
    background-image: url('URL_OF_THE_REMOEV_IMAGE_GOES_HERE');
    background-repeat: no-repeat;
    outline: 1px solid red; /* Remove this after you set the height and width correctly */
    vertical-align: middle; /* Not sure but I think you will need this */
}

.remove:hover {
    background-image: url('REMOVE_LIGHT_PNG_URL_GOES_HERE');
}

答案 1 :(得分:2)

首先不要使用单引号(&#39;),使用双引号(&#34;)或不使用变量引号。

您的代码在单引号下有可变 $ the_job_id

试试这段代码:

<?php
echo '<a href ="javascript:void(0)" onclick ="clickFunc()"><img src="img/remove.png" onmouseover="Over()" onmouseout="Out()"></a>'
?>

并使用此脚本:

    <script>
function clickFunc() {
    document.getElementById("lightpos'.$the_job_id.'").style.display = "block";
    document.getElementById("fadepos'.$the_job_id.'").style.display = "block"
}

function Over() {
    this.src = "img/remove_light.png";
}

function Out() {
    this.src = "img/remove.png";
}
    </script>