简体   繁体   English

如何使用 jQuery 在同一页面上重用 HTML 元素?

[英]How do I reuse an HTML element on the same page using jQuery?

I created a div element called main-middle-column-container in my HTML and styled it with CSS.我在 HTML main-middle-column-container创建了一个名为main-middle-column-container的 div 元素,并使用 CSS 对其进行了样式设置。 Basically, main-middle-column-container will create a twitter-like message box that will have a name, date/time, and the message.基本上, main-middle-column-container将创建一个类似 twitter 的消息框,其中包含名称、日期/时间和消息。

I want to reuse main-middle-column-container and all the code inside of it with jQuery so that when new data comes in, it will use a fresh main-middle-column-container as a template to add in the new values (like how twitter would work).我想用 jQuery 重用main-middle-column-container和其中的所有代码,这样当新数据进来时,它将使用一个新的main-middle-column-container作为模板来添加新值(就像推特的工作方式一样)。 When new data comes in, @username , date/time , and This is a random message. #random当新数据进来时, @usernamedate/timeThis is a random message. #random This is a random message. #random will be replaced with the incoming data or leave the elements empty and have the new data fill it in. This is a random message. #random将替换为传入的数据或将元素留空并让新数据填充它。

I thought about using $('.main-middle-column-container').clone().appendTo('.main-middle-column-wrapper');我想过使用$('.main-middle-column-container').clone().appendTo('.main-middle-column-wrapper'); but that will keep double cloning it (1 box -> 2 box -> 4 box -> 8 box...) instead of cloning it once.但这将保持双重克隆它(1 盒 -> 2 盒 -> 4 盒 -> 8 盒...)而不是克隆一次。 I also have an issue of getting rid of main-middle-column-container before I receive any data because I don't want an empty box on the website I am trying to create.我还有一个问题是在收到任何数据之前摆脱main-middle-column-container ,因为我不希望在我尝试创建的网站上有一个空框。 I want main-middle-column-container to be created right when I get some kind of data/message.我希望在收到某种数据/消息时立即创建main-middle-column-container

CSS and HTML (message box) CSS 和 HTML(消息框)

 .main-middle-column-wrapper{ display: flex; flex-direction: column; width: 49%; } .main-middle-column-container{ width: 100%; } .main-middle-column{ font-family: "Helvetica Neue", Helvetica, Arial ,sans-serif; font-size: 14px; height: auto; width: 100%; background-color: white; padding: 9px 12px; z-index: -2; box-shadow: 0 0 2px 0 lightgray; position: relative; } .main-middle-column:hover{ background-color: hsl(200, 23%, 96%); } .tweet-pic-wrapper{ position: absolute; top: 5px; } .tweet-pic-container{ position: relative; height: 48px; width: 48px; border: 3px solid transparent; border-radius: 100%; overflow: hidden; z-index: 1; display: inline-block; } .tweet-pic{ position: absolute; margin: 0 auto; height: 100%; left: -6px; width: auto; } .title-account-time{ margin-left: 55px; } .msg-title{ font-weight: bold; } .msg-acc-name{ color: #657786; } .msg-acc-name:hover{ cursor: pointer; } .msg-date{ color: #657786; margin-top: 1px; } .tweet-msg{ margin-left: 55px; margin-top: 5px; }
 <div class="main-middle-column-wrapper"> <div class="main-middle-column-container"> <div class="main-middle-column"> <div class="tweet-pic-wrapper"> <div class="tweet-pic-container"> <img src="Picture of the Moon.jpeg" class="tweet-pic" alt="Picture of the moon."> </div> </div> <div class="title-account-time"> <span class="msg-title">My Twitter</span> <span class="msg-acc-name">@username</span> <div class="msg-date">date/time</div> </div> <div class="tweet-msg"> This is a random message. #random </div> </div> </div> </div>

Create a function that returns a Template Literal with the desired HTML markup structure.创建一个函数,该函数返回具有所需 HTML 标记结构的模板文字。 Map your tweets and insert them into a target parent:映射您的推文并将它们插入目标父级:

 const tweets = [ { _id: 321, pic: "https://placehold.it/80x80/0bf", title: "My Twitter", name: "@username", date: "2020-01-18", msg: "this is a story" }, { _id: 231, pic: "https://placehold.it/80x80/f0b", title: "My alter Twitter", name: "@user", date: "2020-01-19", msg: "Again, another story" } ]; const newTweet = tweet => `<div class="main-middle-column"> <div class="tweet-pic-wrapper"> <div class="tweet-pic-container"> <img src="${tweet.pic}" class="tweet-pic" alt="${tweet.title}"> </div> </div> <div class="title-account-time"> <span class="msg-title">${tweet.title}</span> <span class="msg-acc-name">${tweet.name}</span> <div class="msg-date">${tweet.date}</div> </div> <div class="tweet-msg">${tweet.msg}</div> </div>`; const populateNewTweets = (tweets, parent) => { if (!tweets.length) return; $('<div>', { class: 'main-middle-column-container', appendTo: parent, append: tweets.map(newTweet) }); }; populateNewTweets(tweets, '.main-middle-column-wrapper');
 .main-middle-column-wrapper{ display: flex; flex-direction: column; width: 49%; } .main-middle-column-container{ width: 100%; } .main-middle-column{ font-family: "Helvetica Neue", Helvetica, Arial ,sans-serif; font-size: 14px; height: auto; width: 100%; background-color: white; padding: 9px 12px; z-index: -2; box-shadow: 0 0 2px 0 lightgray; position: relative; } .main-middle-column:hover{ background-color: hsl(200, 23%, 96%); } .tweet-pic-wrapper{ position: absolute; top: 5px; } .tweet-pic-container{ position: relative; height: 48px; width: 48px; border: 3px solid transparent; border-radius: 100%; overflow: hidden; z-index: 1; display: inline-block; } .tweet-pic{ position: absolute; margin: 0 auto; height: 100%; left: -6px; width: auto; } .title-account-time{ margin-left: 55px; } .msg-title{ font-weight: bold; } .msg-acc-name{ color: #657786; } .msg-acc-name:hover{ cursor: pointer; } .msg-date{ color: #657786; margin-top: 1px; } .tweet-msg{ margin-left: 55px; margin-top: 5px; }
 <div class="main-middle-column-wrapper"></div> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

I think i have a solution for you, you can create a 'template' and retrieve that template with jquery.我想我有一个解决方案,您可以创建一个“模板”并使用 jquery 检索该模板。 If you put this in your main html file如果你把它放在你的主 html 文件中

<script id="hidden-template" type="text/x-custom-template">
    <div class="main-middle-column-wrapper">
  <div class="main-middle-column-container">
    <div class="main-middle-column">
      <div class="tweet-pic-wrapper">
        <div class="tweet-pic-container">
          <img src="Picture of the Moon.jpeg" class="tweet-pic" alt="Picture of the moon.">
        </div>
      </div>
      <div class="title-account-time">
        <span class="msg-title">My Twitter</span>
        <span class="msg-acc-name">@username</span>
        <div class="msg-date">date/time</div>
      </div>
      <div class="tweet-msg">
        this is a story all about how my life got flipped turned upside down and id like to take a minute and just sit right there id like to tell you how i became a prince in a town called belair.
      </div>
    </div>
  </div>
</div>
</script>

You can get the content with jquery like this您可以像这样使用 jquery 获取内容

var template = $('#hidden-template').html();

Now you have your html 'template' in your javascipt, now your can create more than one of these elements.现在您的 javascipt 中有 html '模板',现在您可以创建多个这些元素。

$('#target').append(template);

Or you can use a better/simpler method with plain javascript或者您可以使用带有普通 javascript 的更好/更简单的方法

const card = ({ img_alt, img_src, title, username, date, msg }) => `
  <div class="main-middle-column-wrapper">
  <div class="main-middle-column-container">
    <div class="main-middle-column">
      <div class="tweet-pic-wrapper">
        <div class="tweet-pic-container">
          <img src="${img_src}" class="tweet-pic" alt="${img_alt}">
        </div>
      </div>
      <div class="title-account-time">
        <span class="msg-title">${title}</span>
        <span class="msg-acc-name">@${username}</span>
        <div class="msg-date">${date}</div>
      </div>
      <div class="tweet-msg">${msg}</div>
    </div>
  </div>
</div>
`;

You can use this as a function to create your elements dynamically with all kinds of data.您可以将其用作一个函数来使用各种数据动态创建您的元素。

The best solution to this would be to use some kind of templating engine, for example Mustache .对此的最佳解决方案是使用某种模板引擎,例如Mustache If that however is out of the question, the solution to your problem would be something like this:但是,如果这是不可能的,那么您的问题的解决方案将是这样的:

jQuery(document).ready(function() {
     /* this should store the container templates clone in a variable */
     mainMiddleContainerTemplate = jQuery(".main-middle-column-container").get(0).clone();

     /* this should remove every main middle container from the view, in case
        you have multiple containers that are not templates, consider adding
        an additional class to your template container */
     jQuery(".main-middle-column-container").remove();
});

function addNewContainer(containerData) {
    var newContainer = mainMiddleContainerTemplate.clone();

    /** add and replace all the data needed on the newContainer **/
    newContainer.find('.message-title').html(containerData.title);
    newContainer.find('.msg-acc-name').html(containerData.accountName);
    ....

    jQuery(".main-middle-container-wrapper").append(newContainer);
}

But still, I would advice you, to use a templating engine for these kinds of stuff.但是,我仍然建议您,为这些类型的东西使用模板引擎。

$('.main-middle-column-container').first().clone().appendTo('.main-middle-column-wrapper');

The key is to select only one element to be cloned.关键是只选择一个要克隆的元素。 First is as good as any other.第一个和其他的一样好。

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

相关问题 如何使用jQuery引用HTML5视频元素? - How do I reference the HTML5 video element using jQuery? 如何使用jQuery检查HTML元素是否为空? - How do I check if an HTML element is empty using jQuery? 如何使用jQuery元素创建/附加生成HTML? - How do I generate html using jQuery element creation/appending? 如何使用 jQuery 在页面上移动元素? - How do I move an element across the page using jQuery? 如何在jQuery中移动HTML元素? - How do I move an HTML element in jQuery? Vanilla JS:如何返回动态html,以便可以在element.innerHTML中重用它? - Vanilla JS: How do I return dynamic html so I can reuse it in element.innerHTML? 我如何通过jquery ajax对html元素进行永久更改,以使其在刷新页面后仍保留? - How do i make changes to an html element through jquery ajax permanent so it remains after refreshing the page? 我通常如何使用JavaScript(jQuery)在HTML中创建元素的副本作为新元素? - How do I conventionally create a replica of an element as a new element in HTML using JavaScript (jQuery)? 如何使用jQuery将页面元素与动态生成的元素包装在一起? - How do I wrap a page element with a dynamically generated element using jQuery? 如何在同一 HTML 页面上显示 HTML GET 请求数据,使用单独的 PHP 文件来获取它? - How do I display the HTML GET request data on the same HTML page, using a separate PHP file to fetch it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM