简体   繁体   English

使用javascript动态添加和删除网页上的元素

[英]Adding and removing elements on a web page dynamically using javascript

So I'm using Twitter Bootstrap to create a web page, and I'd like to use their "Alerts" class to dynamically create and dismiss alerts at the bottom of my page. 因此,我正在使用Twitter Bootstrap创建网页,并且希望使用其“警报”类在页面底部动态创建和关闭警报。 Basically my web page is used to monitor a wireless data acquisition system, so I'd like to be able to dynamically display messages related to that system, ie "Warning, Sensor 1 is not responding", and then be able to dismiss it dynamically when the event has passed, or have the user dismiss it. 基本上,我的网页用于监视无线数据采集系统,因此我希望能够动态显示与该系统相关的消息,即“警告,传感器1没有响应”,然后能够动态将其关闭事件结束后,或让用户将其关闭。 I'm more of an embedded systems guy, and haven't done much web development, so I'm really not sure where to start. 我更喜欢嵌入式系统,并且还没有做太多的Web开发工作,所以我真的不确定从哪里开始。 My first inclination would be to do something like this: 我的第一个倾向是做这样的事情:

<div id="Alert1"></div>
<div id="Alert2"></div>
...

And create enough divs at the bottom of my page to display a reasonable number of messages, then dynamically change them in code with something like: 并在页面底部创建足够的div以显示合理数量的消息,然后使用类似以下内容的代码动态更改它们:

var Alert1 = document.getElementById("Alert1");
Alert1.className = "alert alert-warning";
$('#Alert1').html("Error: Unable to write to logfile");

I can't imagine that this is a very good way to do it, though, and I'd have to have some way to manage what divs were in use, etc. What is a better way to dynamically create and remove these elements? 但是,我无法想象这是一个很好的方法,而且我必须有某种方法来管理使用的div等。动态创建和删除这些元素的更好方法是什么?

Using jQuery you can use append to dynamically add an element to the page. 使用jQuery,您可以使用append将元素动态添加到页面中。

  <div class="alerts"></div>

In JavaScript: 在JavaScript中:

   $(".alerts").append("<div id='alert1'>Warning</div>");

Similarly you can remove the element using the remove() function. 同样,您可以使用remove()函数删除元素。

You don't need to create a <div> for any and all error messages you have. 您无需为所有错误消息创建<div> Just create one <div> and dynamically fill in the appropriate text (or HTML) of the currently active message. 只需创建一个<div>并动态填充当前活动消息的适当文本(或HTML)。

Sample code: 样例代码:

// define this function globally
(function (exports) {

  var messages = {};
  function addMessage(type, msg) {
    if (typeof messages[type] === "undefined") {
      messages[type] = [];
    }
    messages[type].push(msg);
    render();
  }

  function render() {
    var html = "";
    for (type in messages) {
      if (messages.hasOwnProperty(type)) {

        for (var i=0, len=messages[type].length; i<len; i++) {
          html += type + ": " + messages[type][i];
        }
      }
    }
    $("#Alert").html(html);
  }
  exports.addMessage = addMessage;
})(window);

// somewhere in your code
addMessage("Error", "Unable to write to logfile");

It would be even better to declare "Error" as a constant/variable somewhere: 最好在某处将“错误”声明为常量/变量:

var ERR_ERROR = "Error";
var ERR_WARNING = "Warning";

You can define a template for your alerts, holding the message and the type of the message. 您可以为警报定义模板,其中包含消息和消息类型。

Then according to the type of the message you would append the message into the page. 然后,根据消息的类型,您可以将消息添加到页面中。

Consider the following function 考虑以下功能

function addAlert(type, message) {
_.templateSettings.variable = "element";
var tpl = _.template($("#alertTemplate").html());
var tplData = {
    message: message,
    type: type
  };
$("#mainContainer").append(tpl(tplData));//the div or container where you want your messages to appear
}

And the template would be 模板将是

<script type="text/html" id="alertTemplate">
    <div class = "alert alert-<%= element.type %>" > <%= element.message %> </div>
</script>

and of course the container of your alerts 当然还有警报的容器

<div id="mainContainer"> 

</div>

Then in your alert handler you would call addAlert with the appropriate parameters. 然后,在警报处理程序中,您将使用适当的参数调用addAlert。

and to remove all the alerts 并删除所有警报

  $("#mainContainer").find('.alert').remove();

You can find working example at http://jsfiddle.net/hatemalimam/EpM7W/6/ 您可以在http://jsfiddle.net/hatemalimam/EpM7W/6/找到工作示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM