Home  >  Article  >  Backend Development  >  javascript - 部署到线上的项目,写在js文件中需要动态加载的图片路径怎么去查找?

javascript - 部署到线上的项目,写在js文件中需要动态加载的图片路径怎么去查找?

WBOY
WBOYOriginal
2016-06-06 20:35:01929browse

<code><img class="share-dream" src="<?php%20echo%20%24thisActAssetsRoot;?>img/grades.png" alt="分数">
</code>

在首页通过这样的方式去获取静态资源的路径,但是在js文件中我需要去动态添加的一些图片就不显示了,js里不能写php语句,我该怎么去查找呢?
比如说想点击这张图片之后换成另一张图片,这个click事件我是写在一个单独的js文件里,在js文件里怎么去获取要替换的图片呢?

<code>$('.share-dream').click(function(){
        $(".share-dream").attr(
        "src",
        "<?php echo $thisActAssetsRoot;?>img/shareBtnClick.png")
    })
//我可以这么写么
</code>

回复内容:

<code><img class="share-dream" src="<?php%20echo%20%24thisActAssetsRoot;?>img/grades.png" alt="分数">
</code>

在首页通过这样的方式去获取静态资源的路径,但是在js文件中我需要去动态添加的一些图片就不显示了,js里不能写php语句,我该怎么去查找呢?
比如说想点击这张图片之后换成另一张图片,这个click事件我是写在一个单独的js文件里,在js文件里怎么去获取要替换的图片呢?

<code>$('.share-dream').click(function(){
        $(".share-dream").attr(
        "src",
        "<?php echo $thisActAssetsRoot;?>img/shareBtnClick.png")
    })
//我可以这么写么
</code>

引入js文件怎么可能执行PHP代码
我一般做法是在那个引入JS文件的模板HTML里放隐藏域,比如

<code><input type="hidden" id="thisActAssetsRoot" value="<?php echo $thisActAssetsRoot;?>">
</code>

然后js文件里面通过获取这隐藏域的值实现动态

<code>$('.share-dream').click(function(){
        $(".share-dream").attr(
        "src",$('#thisActAssetsRoot').val()+"img/shareBtnClick.png")
    })
</code>

那么问题来了,谁说 JS 里面不可以写 PHP 的?

<code>function assest(url) { return "<?php echo $thisActAssetsRoot; ?>"+url; }
console.log( assest("img/grades.png") );
</code>

这个一般需要后端在js中进行配置(后端模板)。
比如:

<code>javascript</code><code>var ACTION_SET = {
   host:''
}
</code>

然后前端调用即可。

js里想写php要把js直接写在php页面里

一般的话,如果是公共数据,配置在公共模板中

<code>javascript</code><code><script>
    var cVar = {
        "SITE_URL": "<?php ?>",
        "IMG_DOMAIN": "<?php ?>"
    };
</script>
</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn