简体   繁体   中英

Javascript replace content of html

I am trying to replace some content of html page. I successfully pick it to string, but when I try to put it back, html shows me "Undefined"

var count = 1;
var count2 = 0;
document.getElementById("element1").onkeyup = function () {
    if (count2 === 0) {
        var content1 = document.getElementById("element2").innerHTML;
        count2 = 1;
    }
    if (document.getElementById("element1").value !== "") {
        document.getElementById("element2").innerHTML = "";
        count = 0;
    } else if (count === 0) {
        document.getElementById("element2").innerHTML = content1;
        count = 1;
    }
};

Anybody knows why?

这是一个悬挂问题,在函数的开头声明content1,而不是在if状态中声明

Ok I have got it solved. I had to make content1 global variable.

var count = 1;
var content1;
window.onload = function () {
    content1 = document.getElementById("element1").innerHTML;
};
document.getElementById("element2").onkeyup = function () {

    if (document.getElementById("element2").value !== "") {
        document.getElementById("element1").innerHTML = "";
        count = 0;
    } else if (count === 0) {
        document.getElementById("element1").innerHTML = content1;
        count = 1;
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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