0

我正在尝试即时修改我<div>的。我有(开始)位置和文本。我必须在这个位置插入文本。

date = {
    position: 5,
    text: 'nice'
}

<div class="something">I like cookies</div>

你知道没有 substring() 或 substr() 的情况。

4

3 回答 3

2

怎么用slice()

date = {
    position: 7,
    text: 'nice '
}

var elem = document.getElementsByClassName('something')[0],
    txt  = elem.innerHTML;
    _txt = txt.slice(0, date.position) + date.text + txt.slice(date.position, txt.length);

elem.innerHTML = _txt;

小提琴

于 2013-05-28T21:42:50.470 回答
0
var data = {
        text: 'nice',
        position: 5
    },
    element1 = document.getElementsByClassName("something")[0],
    str1 = element1.innerHTML, //assume you can use getElementsByClassName; otherwise write a function for it.
    i,
    output = '';

for (i = 0; i < str1.length; i++) {
    if (i === data.position) {
        output += str1[i] + data.text;
    }
    output += str1[i]
}
element1.innerHTML = output;
于 2013-05-28T21:46:30.487 回答
0

怎么样slice

"foo bar".slice(0, 3) == "foo"
"foo bar".slice(3)    == " bar"
"foo bar".slice(-3)   == "bar"
"foo bar".slice(-2)   == "ar"

因此,鉴于您的示例,您最终会得到如下结果:

var date = {
    position: 5,
    text: 'nice'
};

var foo = $('<div class="something">I like cookies</div>').text();
var bar = foo.slice(0, date.position) + date.text + foo.slice(date.position);

于 2013-05-28T21:46:52.813 回答