简体   繁体   English

使用JavaScript在div中的位置'x'处插入文本

[英]Insert text at position 'x' in a div using JavaScript

I'm trying modify my <div> on the fly. 我正在尝试修改我的<div> I have (start) position and text. 我有(开始)位置和文字。 I must insert text at this position. 我必须在这个位置插入文字。

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

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

Do you have any idea how it do without substring() or substr(). 如果没有substring()或substr(),你知道它是怎么做的吗?

How about using slice() ? 使用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;

FIDDLE 小提琴

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;

How about with slice ? slice怎么样?

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

So given your example you would end up with something like this: 所以考虑到你的例子你会得到这样的东西:

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);

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

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