将span数组的第一个索引和最后一个索引分配给对象

时间:2012-01-16 20:31:44

标签: javascript jquery html

我正在用网页制作某种电影。为此,我必须用文本的字符做某些事情。 html看起来像这样:

<div id="section_1" style="display: none;">
        <p>Goede typografie stimuleert het lezen en heeft als gevolg dat men zo weinig mogelijk moeite hoeft te doen om  een tekst te kunnen lezen. Het moet zo min mogelijk weerstand oproepen om een tekst te kunnen begrijpen.</p>
</div>

<div id="section_2" style="display: none;">
    <p>Het vermogen om zeer snel te kunnen lezen en zodoende onze tijd effectief te kunnen gebruiken, hangt vooral af van de wijze waarop de boodschap typografisch is vormgegeven.</p>
</div>

要使用这些字符,我会翻阅每一个字母。如下所示:

var spans = new Array();


// span every character
for(var i = 0; i < data.sections.length; i++) {
    //spanEachChar("#section_"+i);
    $("#section_"+i).children().andSelf().contents().each(function(index){
    if (this.nodeType == 3) {
        var $this = $(this);
        $this.replaceWith($this.text().replace(/\w/g, function(text,index2) {
            return "<span id="+index2+">" + text + "</span>";
        }));
    }
    });
}

// store each span in an array
$("#content span").each(function() {
    spans.push($(this));
});

console.log("spans.length "+spans.length);

// get them like this
var span = spans[20];

我还有一个数组/对象(不知道它叫什么),我存储每个部分的持续时间,以便在一定时间后显示新的部分。

  var data = {
            sections:[{
                id: 0,
                duration: 0,
                firstSpanIndex: -1,
                lastSpanIndex: -1
            }, {
                id: 1,
                duration: 7,
                firstSpanIndex: -1,
                lastSpanIndex: -1
            }, {
                id: 2,
                duration: 7,
                firstSpanIndex: -1,
                lastSpanIndex: -1
            }]
    }

如上所示,每个div都有一个名为spans的数组,例如'section_2',我想存储firstSpanIndex和last lastSpanIndex。我想这也许可以在我跨越每个角色的部分完成,但我不知道如何。 我希望你们理解我的问题,解释起来并不容易。


更新

感谢您的帮助。它对学习的目的很有帮助,但不是我想要的。我做了一个图像,以便更清楚我想要什么。

example of what i want

我希望图像足够清晰。它显示了每个字符串分开的4个paragraps。所有这些跨度都在一个阵列中。在那个数组中没有更多(所以没有第一个或最后一个)。然后data.sections保存每个段落的信息,比如id(等于索引atm)和它应显示的秒数(图中未显示)以及span数组的开始和结束索引。

4 个答案:

答案 0 :(得分:2)

jQuery的.first().last()功能是否可以满足您的需求? 例如,你能说;

// Grabs the first span only, then it's index value
firstSpanIndex: $this.children("span").first().index();
  

更新 * 再次更新,小提琴也移动了 *

仍然不确定你究竟想做什么,但我做了一个快速的小提琴,我认为你会尝试做什么。 - &GT; my jsFiddle MOVED!!! HERE!!!

我重写了一下你的代码并更改了每个部分以包含一个名为section的类。 我这样做是因为看起来你的部分会被html所知,但不一定是他们所在的对象。我将在下面解释重写:

//  This first line simply calls each section by its class tag and begins the means of operation
$(".section").each(function(i) { // using var i in the function i can keep up with 0 based index of each section i am going thru
    if (!data.sections[i]) { // this simply checks to see if this section exist in array yet, if not, we create it with base params
        data.sections[i] = [{
            id: i,
            duration: 0,
            firstSpanIndex: -1,
            lastSpanIndex: -1
        }]
    };
    // add your type oof id to each section if you still want it
    var $this = $(this).attr({ id: "section_"+i });
    // this .each is like a "catchall" to ensure you go thru wach p child of your section and span each char
    $this.children("p").each(function(ii) {
        // save the initial text to a variable for spaning
        var tt = $(this).text();
        // begin your spanning technique, not bad btw
        $(this).html(tt.replace(/\w/g, function(txt, id2) {
            return "<span id="+id2+">"+txt+"</span>";
        }));
        // update the section information in your data array
        data.sections[i].firstSpanIndex = $(this).children("span").first();
        data.sections[i].lastSpanIndex = $(this).children("span").last();
        // made a fatal flaw using .extend as each section of spans get the same id presence, 
        // changed this to .merge which will extend the array regardless of index values
        $.merge(true, spans, $(this).children("span"));
    });
});

请务必查看Fiddle以获取更多信息和工作视图

答案 1 :(得分:0)

对于每个部分,在数据属性中写入第一个和最后一个索引。

对于firstIndex和LastIndex,您需要根据您所在的部分获得偏移量。

对于firstIndex,检查span字符是否是循环中的第一个 - 如果是,则计算它的索引值。

对于lastIndex,只需保持设置偏移值(循环中的最后一次,它将设置正确的值。)

然后,在完成之后的其他地方,您可以通过为每个跨度抓取数据属性值'data-first-index'和'data-last-index'来构建sections数组。

for(var i = 0; i < data.sections.length; i++) {

  // get the offset for this section - if it's the first one, set it's value to -1
  // if it's not the first one, set it as the data-last-index value
  var offset = i == 0 ? -1 : $('#section_'+i).attr('data-last-index');

  // for each character in your section
  for(var j = 0; j < <number of characters in the section>; j++) {

    var $el = $('#section_'+i);  // cache the dom el

    // set first index - it's simply just the previous lastindex + curr pos + 1
    if (index == 0) {
      $el.attr('data-first-index', offset + j + 1);
    }

    // set last index (everytime, last one in the loop is the last index)
    $el.attr('data-last-index', offset + j);

  });
}

// now you can build your sections array and populate the firstIndex and lastIndex values
// by going $('section_X').attr('data-first-index') => firstIndex value
// and  $('section_X').attr('data-last-index') => lastIndex value

答案 2 :(得分:0)

您可能需要查看thisthis。单击链接时使用谷歌浏览器或它们将无法正常显示。他们或许可以帮助你实现你想要实现的目标。

答案 3 :(得分:0)

如果我抓住了你,你可能需要这个:

<head>
<script>

$(document).ready(function(){

var data = {
    sections: [
        {
            id: 0,
            duration: 0,
            firstSpanIndex: -1,
            lastSpanIndex: -1
        }, {
            id: 1,
            duration: 7,
            firstSpanIndex: -1,
            lastSpanIndex: -1
        }, {
            id: 2,
            duration: 7,
            firstSpanIndex: -1,
            lastSpanIndex: -1
        }]
}   

var spans = new Array();


// span every character
var counter = 0;
for(var i = 0; i < data.sections.length; i++)
{
    //spanEachChar("#section_"+i);
    $("#section_"+i).children().andSelf().contents().each(function(index)
    {
        if (this.nodeType == 3)
        {
            var $this = $(this);
            $this.replaceWith($this.text().replace(/\w/g, function(text,index2)
            {
                if (data.sections[i].firstSpanIndex == -1)
                {
                    data.sections[i].firstSpanIndex=counter;
                }
                data.sections[i].lastSpanIndex=counter;
                counter++;
                return "<span id="+index2+">" + text + "</span>";
            }));
        }
    });
}

// store each span in an array
$("#content span").each(function() {
    spans.push($(this));
});

//console.log("spans.length "+spans.length);

// get them like this
//var span = spans[22];
//console.log(span);

console.log(data);

});
</script>
</head>

<body>

<div id="content">
    <div id="section_1" style="display: none;">
        <p>Goede typografie stimuleert het lezen en heeft als gevolg dat men zo weinig mogelijk moeite hoeft te doen om  een tekst te kunnen lezen. Het moet zo min mogelijk weerstand oproepen om een tekst te kunnen begrijpen.</p>
    </div>

    <div id="section_2" style="display: none;">
        <p>Het vermogen om zeer snel te kunnen lezen en zodoende onze tijd effectief te kunnen gebruiken, hangt vooral af van de wijze waarop de boodschap typografisch is vormgegeven.</p>
    </div>
</div>

</body>

请注意,data.sections [0] .firstSpanIndex和data.sections [0] .lastSpanIndex保持为-1,因为没有div with section_0 所以第一个可用范围将是{{1 data.sections 1

这里有一个小提琴http://jsfiddle.net/u5MMJ/

这是另一个带div section_0的人,以显示差异http://jsfiddle.net/QqjHK/

(当然在两种情况下都要检查控制台)