2013-04-09 29 views
1

我有一个产品标题“枕头BALANCE紫色”,我希望在第二个字到换行符后。如下所示。第二个字和着色之后的换行

枕头BALANCE
紫色

这个称号有一个类可以说 “称号”。我使用下面的代码来改变第一个单词“Pillow”的颜色,但我需要改变第二个单词的颜色,当然也要让第三个单词进入第二行。任何帮助都会有所帮助。

//add span to first word of module title, page heading 
window.addEvent ('domready', function() { 
    var els = $$('.art-postcontent h2 a, .art-postcontent h2 a:link, .art-postcontent h2 a:hover, .art-postcontent h2 a:visited, .art-blockcontent h2 a, .art-blockcontent h2 a:link, .art-blockcontent h2 a:hover, .art-blockcontent h2 a:visited'); 
    if (!els.length) return; 
    els.each (function(el){ 
     var html = el.innerHTML; 
     var text = el.get("text"); 
     var pos = text.indexOf(' '); 
     if (pos!=-1) { 
      text = text.substr(0,pos); 
     } 
     el.set("html", el.get("text").replace(new RegExp (text), '<span class="first-word">'+text+'</span>')); 

    }); 
}); 
+0

查一查'分裂()'。这将有所帮助。通常情况下,您会希望从DOM获取字符串。你做了第一部分。做所有三个字。然后构建要替换它们的HTML并放回。 (你用正则表达式做了什么可能不是个好主意,请使用字符串连接。) – 2013-04-09 15:10:30

回答

0

使用split()函数应该可以帮到你。

var str = 'pillow BALANCE purple'; 
var substr = str.split(' '); //splits the string at each space (&nbsp;) 

$('#firstLine').text(substr[0] + substr[1]); //adds first two words to first line 
$('#secondLine').text(substr[2]); //add third word to second line 

HTML:

<div id="firstLine"></div> 
<br />  <!-- Break will put the next div on a new line --> 
<div id="secondLine"></div> 
+0

感谢您的回答,但它没有奏效。也许我没有正确解释我需要什么。 “Pillow BALANCE purple”是产品名称,由此代码调用<?php echo $ productTitle?>您可以在http://www.ninetteart.com/nart上查看它。这是任何产品的名称,我真的需要在第一行中有前两个字,其他字在下面。我不知道这是否可能,当然如果我正在解释我想要的是正确的。无论如何,感谢您的时间帮助。 – 2013-04-15 14:59:44

+0

好吧,在看贴的例子之前,我可以告诉你一个约定是必要的。你说你想要前两个单词...所以只要你的产品遵循惯例“单词单词”(每个单词后跟一个空格),那么这确实会起作用。 split('')接受字符串,并在每个空格处将它拆分,将子字符串弹出到数组中。那么你可以通过调用数组的索引来单独调用每个单词...所以前两个单词总是分别是array [0]和array [1] – 2013-04-15 15:07:57

相关问题