Как я могу реализовать prepend и append с обычным JavaScript?

function decimal_notation($float) {
        $parts = explode('E', $float);

        if(count($parts) === 2){
            $exp = abs(end($parts)) + strlen($parts[0]);
            $decimal = number_format($float, $exp);
            return rtrim($decimal, '.0');
        }
        else{
            return $float;
        }
    }

работает с 0.000077240388

140
задан AstroCB 21 August 2014 в 04:33
поделиться

3 ответа

Возможно, вы спрашиваете о методах DOM appendChild и insertBefore .

parentNode.insertBefore(newChild, refChild)

Вставляет узел newChild как дочерний для parentNode перед существующий дочерний узел refChild . (Возвращает newChild .)

Если refChild имеет значение null, newChild добавляется в конец списка дети. Эквивалентно и более удобно использовать parentNode.appendChild (newChild) .

140
ответ дан 23 November 2019 в 22:57
поделиться

Вот фрагмент для начала:

theParent = document.getElementById("theParent");
theKid = document.createElement("div");
theKid.innerHTML = 'Are we there yet?';

// append theKid to the end of theParent
theParent.appendChild(theKid);

// prepend theKid to the beginning of theParent
theParent.insertBefore(theKid, theParent.firstChild);

theParent.firstChild даст нам ссылку на первый элемент внутри theParent и поместит theKid перед ним.

158
ответ дан 23 November 2019 в 22:57
поделиться

Вы не дали нам подробностей, но я думаю, вы просто спрашиваете, как добавить контент в начало или конец элемента? Если да, то вот как это сделать довольно просто:

//get the target div you want to append/prepend to
var someDiv = document.getElementById("targetDiv");

//append text
someDiv.innerHTML += "Add this text to the end";

//prepend text
someDiv.innerHTML = "Add this text to the beginning" + someDiv.innerHTML;

Довольно просто.

26
ответ дан 23 November 2019 в 22:57
поделиться
Другие вопросы по тегам:

Похожие вопросы: