使用 javascript 更新 div 的内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5255738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:33:21  来源:igfitidea点击:

Updating the content of a div with javascript

javascriptjqueryhtml

提问by Russell Strauss

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:

我没有尝试在我的网站上创建大量不同的页面,而是尝试在单击导航栏中的不同项目以更新维护 div 内容时更新单个 div 的内容。我试图找到一个使用 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>

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.

当我只尝试更新文本时,这很好用,但是当我在其中放置一个 img 标签时,如您所见,它停止工作。

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?

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

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.

我没有被 Javascript 困住。jQuery 也可以工作,只要它一样简单或容易。我想创建一个函数,它只会让我传入我想要更新的任何 HTML 并将其插入 div 标签并取出“旧”HTML。

回答by Cameron

You just have some escaping issues:

你只是有一些逃避的问题:

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

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' answerconcerning escaping the <and >in the HTML):

内部'需要转义,否则 JS 引擎会看到ReplaceContentInContainer('example1div', '<img src='加上一些由后续2.jpg'>'). 将调用更改为(对cHao关于转义<>在 HTML 中的回答的提示):

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

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):

使用 jQuery 执行此操作的一种简单方法是将 ID 添加到您的链接(例如“idOfA”),然后使用该html()函数(这比使用更跨平台innerHTML):

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

回答by Ori

First of all, don't put complex JavaScript code in hrefattributes. It's hard to read or to maintain. Use the <script>tag or put your JavaScript code in a separate file altogether.

首先,不要在href属性中放置复杂的 JavaScript 代码。很难阅读或维护。使用该<script>标签或将您的 JavaScript 代码完全放在一个单独的文件中。

Second, use jQuery. JavaScript is a strange beast: the principles underlying its patterns were not designed with modern-day web development in mind. jQuery gives you lots of power without miring you in JavaScript's oddities.

其次,使用jQuery。JavaScript 是一头奇怪的野兽:其模式背后的原则在设计时并未考虑到现代 Web 开发。jQuery 为您提供了强大的功能,而不会让您陷入 JavaScript 的古怪之处。

Third, if your goal is to avoid having to endlessly duplicate the same basic structure for all (or many) of your pages, consider using a templating system. Templating systems allow you to plug in specific content into scaffolds containing the common elements of your site. If it sounds complicated, it's because I haven't explained it well. Google it and you'll find lots of great resources.

第三,如果您的目标是避免为所有(或许多)页面无休止地复制相同的基本结构,请考虑使用模板系统。模板系统允许您将特定内容插入包含站点常见元素的脚手架中。如果听起来很复杂,那是因为我没有很好地解释它。谷歌一下,你会发现很多很棒的资源。

Relying on JavaScript for navigation means your site won't be indexed properly by search engines and will be completely unusable to someone with JavaScript turned off. It is increasingly common--and acceptable--to rely on JavaScript for basic functionality. But your site should, at minimum, provide discrete pages with sensible and durable URLs.

依靠 JavaScript 进行导航意味着您的网站不会被搜索引擎正确编入索引,并且对于关闭 JavaScript 的人来说将完全无法使用。依赖 JavaScript 来实现基本功能的情况越来越普遍——也可以接受。但是您的站点至少应该提供具有合理且持久的 URL 的离散页面。

Now, all that said, let's get to your question. Here's one way of implementing it in jQuery. It's not the snazziest, tightest implementation, but I tried to make something very readable:

现在,说了这么多,让我们来回答你的问题。这是在 jQuery 中实现它的一种方法。这不是最时髦、最紧凑的实现,但我试图使一些非常可读的东西:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>jQuery Example</title>
    <style type="text/css" media="all">
        /* all content divs should be hidden initially */
        .content {
            display: none;
        }

        /* make the navigation bar stand out a little */    
        #nav {
            background: yellow;
            padding: 10px;
        }
    </style>
</head>
<body>
    <!-- navigation bar -->
    <span id="nav">
        <a href="#about_me">about me</a> |
        <a href="#copyright">copyright notice</a> |
        <a href="#my_story">a story</a>
    </span>

    <!-- content divs -->
    <div class="content" id="about_me">
        <p>I'm a <strong>web developer</strong>!</p>
    </div>
    <div class="content" id="copyright">
        <p>This site is in the public domain.</p>
        <p>You can do whatever you want with it!</p>
    </div>
    <div class="content" id="my_story">
        <p>Once upon a time...</p>
    </div>

    <!-- jquery code -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
    <script>
    // Wait for the document to load
    $(document).ready(function() {
        // When one of our nav links is clicked on,
        $('#nav a').click(function(e) {
            div_to_activate = $(this).attr('href'); // Store its target
            $('.content:visible').hide(); // Hide any visible div with the class "content"
            $(div_to_activate).show(); // Show the target div
        });
    });
    </script>
</body>
</html>

Ok, hope this helps! If jQuery looks attractive, consider starting with this tutorial.

好的,希望这有帮助!如果 jQuery 看起来很有吸引力,请考虑从本教程开始。

回答by cHao

Your main problem with your example (besides that innerHTMLis not always supported) is that <and >can easily break HTML if they're not escaped. Use &lt;and &gt;instead. (Don't worry, they'll be decoded before the JS sees them.) You can use the same trick with quotes (use &quot;instead of "to get around quote issues).

您与您的一例的主要问题(除了那innerHTML并不总是支持)是<>可以轻松打破HTML,如果他们没能逃脱。使用&lt;&gt;代替。(别担心,它们会在 JS 看到它们之前被解码。)您可以对引号使用相同的技巧(使用&quot;而不是"绕过引号问题)。