简体   繁体   English

Javascript调用隐藏和存储字符串文本作为LI标签中的变量

[英]Javascript invoke hide and store string text as variable within LI tag

Using this question I was able to hide a list element that contained some string text. 使用这个问题,我能够隐藏包含一些字符串文本的列表元素。 I'd like to re-use everything within these <LI></LI> tags however someplace else within the page. 我想重用这些<LI></LI>标记中的所有内容,但是要重用页面中的其他位置。 The entire contents of the LI tags can vary but will share the one common element I'm able to invoke the hide with. LI标签的全部内容可以变化,但是将共享一个我可以用来调用hide的公共元素。 Is there some way to adjust this code to store everything found as a variable after I successfully hide it? 在成功隐藏所有代码后,是否可以通过某种方式来调整此代码以将找到的所有内容存储为变量?

Event.observe(window, "load", function(){

$$("li:contains('Full Listing Information:')").invoke("hide");
});

Just assign it to a variable. 只需将其分配给变量即可。

var listings;
Event.observe(window, "load", function(){
    listings = $$("li:contains('Full Listing Information:')");
    listings.invoke("hide");
});

Imagine you have a div#output elsewhere on the page, and you want to put the text of your list items into it, each wrapped in an h2. 想象一下,您在页面上的其他地方有一个div#output ,并且您想要将列表项的文本放入其中,每个项目都包装在h2中。 Let's also imagine that you want to leave the other list items (the ones that don't match your selector) alone where they are. 我们还假设您想将其他列表项(与选择器不匹配的项)留在原处。 This should do the trick: 这应该可以解决问题:

document.observe('dom:loaded', function(){
  var listings = $$("li:contains('Full Listing Information:')").invoke('hide').map(function(elm){ return elm.innerText });
  var t = new Template('<h2>#{text}</h2>')
  listings.each(function(str){
    $('output').insert(t.evaluate({text: str}))
  });
});

Inside the first line, you first hide each of the matching list items, then extract the text content from them into an array. 在第一行中,您首先隐藏每个匹配的列表项,然后将它们中的文本内容提取到数组中。 The last three lines iterate over that array, building a new h2 each turn, and inserting it into your recipient div. 最后三行遍历该数组,每转一个新的h2,然后将其插入到您的收件人div中。 The outer wrapper just makes certain that the DOM is stable before you run this. 运行此操作之前,外部包装程序仅确定DOM是稳定的。 It can run before the rest of the page is visible, so you shouldn't have the Flash Of Unstyled Content to worry about. 它可以在页面其余部分可见之前运行,因此您不必担心Flash of Unstyled Content。

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

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