通过 javascript 插入内嵌图像
我编写了一个脚本,通过 JSONP 获取图像 url,然后我需要将其写入浏览器,这是一个状态图像,为 onling.png、offline.png 等,
我的脚本如下所示。
<div id='STATUSDIV'></div>
<script language=javacsript type=text/javascript src=http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js></script>
<script type="text/javascript">$(document).ready(function()
{
$.getJSON('http://MYSSERVERNAME.COM/get.php?callback=?','q=value&index'+Math.random(),
function(res)
{
document.getElementById('STATUSDIV').innerHTML = ("<img src='"+res.img+"' />");
});
});
</script>
使用此代码,我可以在 div statusdiv 内获取图像,但是我不能在单个页面上使用相同的代码块两次,因为两者都指向相同的 div。
我能做的快速事情是,我可以要求最终用户在每个页面上多次复制此代码来更改 div id,以便该图像将加载到不同的 div 上。
但我希望在复制的任何地方都有相同的代码,只内联写入图像。一种创建元素并写入该元素。但这不起作用。 document.write 也不起作用,因为它取代了所有内容。
有没有一种方法,当这个代码块调用时,代码不编写innerhtml,而是在页面上创建一个动态div并在其中写入图像。这个图像写入和创建 div 发生在调用脚本块的地方。这样,如果在页眉和页脚中调用相同的脚本,状态图像将同时出现在页眉和页脚上。
I wrote one script which gets an image url through JSONP, and then I needed to write that to browser, this is a status image which is onling.png, offline.png and so on
my script looks like this.
<div id='STATUSDIV'></div>
<script language=javacsript type=text/javascript src=http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js></script>
<script type="text/javascript">$(document).ready(function()
{
$.getJSON('http://MYSSERVERNAME.COM/get.php?callback=?','q=value&index'+Math.random(),
function(res)
{
document.getElementById('STATUSDIV').innerHTML = ("<img src='"+res.img+"' />");
});
});
</script>
using this code, I am able to get an image inside div statusdiv, however I can not use same code block twice on single page as both will point to same div.
quick thing I can do is that I can ask end user who will copy this code multiple time on each page to change div id so that that image will load on differnt div.
But I wanted to have same code wherever copied just writes image inline. kind of createelement and write in that element. but thats not working. document.write does not work either as it replaces everything.
Is there a way that when this code block called, Instead of writing innerhtml, code creates a dynamic div right there on the page and writes image in that. and this image writing and creating div happens where script block is called. so that If same script is called in header and footer, status image will appear on both header and footer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我所知道的最干净的方法是为您的代码创建一个函数,该函数应该很早就包含在页面中,以便它随处可用:
脚本:
然后,在页面中有人想要状态图像的任何位置,他们可以放置此内联 在进行函数调用的位置动态插入具有唯一 div ID 的 div,并跟踪闭包中使用的每个 ID。
The cleanest way I know of is to create a function for your code that should get included very early in the page so it's available everywhere:
Then, any place in the page where someone wants a status image, they can put this inline script:
This dynamically inserts a div with a unique div ID at the place that the function call is made and it keeps track of each ID that is used in the closure.