用javascript更新div的内容 [英] Updating the content of a div with javascript

查看:108
本文介绍了用javascript更新div的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与其试图在我的网站上创建大量不同的页面,我试图在导航栏中的不同项目单击以更新maint div内容时更新单个div的内容。我试图找到一个使用Javascript的简单示例:

Rather than trying to create tons of different pages on my website, I'm trying to update the content of a single div when different items in the navbar are click to update the maint div content. I tried to find a simple example using Javascript:

        <script type="text/javascript">
            function ReplaceContentInContainer(id,content) {
                var container = document.getElementById(id);
                container.innerHTML = content;
            }
        </script>


          <div id="example1div" style="border-style:solid; padding:10px; text-align:center;">
            I will be replaced when you click.
        </div>
        <a href="javascript:ReplaceContentInContainer('example1div', '<img src='2.jpg'>' )">
            Click me to replace the content in the container.
        </a>

当我只尝试和更新文本时,这很好,但是当我在其中放置一个img标签时,你可以看到,它停止工作。

This works just fine when I only try and update text, but when I put an img tag in there, as you can see, it stops working.

或者
1)我如何尝试这样做有什么问题?
或2)什么是更好/更简单的方法来做到这一点?

Either 1) what is the problem with how I am trying to do it? or 2) What is a better/easier way to do it?

我没有坚持使用Javascript。 jQuery也可以工作,只要它简单或容易。我想创建一个函数,让我通过我想要更新的任何HTML,并将其插入到div标签中,并取出旧HTML。

I'm not stuck on Javascript. jQuery would work too, as long as it is just as simple or easy. I want to create a function that will just let me pass in whatever HTML I want to update and insert it into the div tag and take out the 'old' HTML.

推荐答案

您只是有一些转义问题:

You just have some escaping issues:

ReplaceContentInContainer('example1div', '<img src='2.jpg'>')
                                                   ^     ^

code>'需要被转义,否则JS引擎会看到 ReplaceContentInContainer('example1div','< img src ='加上后续的 2.jpg'>')产生的一些语法错误。将该呼叫更改为(将帽子的顶端改为 cHao'回答有关在HTML中转义< / code>和>

The inner ' need to be escaped, otherwise the JS engine will see ReplaceContentInContainer('example1div', '<img src=' plus some syntax errors resulting from the subsequent 2.jpg'>'). Change the call to (tip of the hat to cHao' answer concerning escaping the < and > in the HTML):

ReplaceContentInContainer('example1div', '&lt;img src=\'2.jpg\'&gt;')

使用jQuery完成这项工作的一个简单方法是在链接中添加一个ID(例如idOfA) ,然后使用 html()功能(这比使用 innerHTML )更具跨平台性:

A simple way to do this with jQuery would be to add an ID to your link (say, "idOfA"), then use the html() function (this is more cross-platform than using innerHTML):

<script type="text/javascript">
    $('#idOfA').click(function() {
        $('#example1div').html('<img src="2.jpg">');
    });
</script>

这篇关于用javascript更新div的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆