using javascript to change some text into an input field when clicked on

前端 未结 3 507
有刺的猬
有刺的猬 2020-12-24 08:39

I\'m trying to make a page that has some editabable fields, but I only want them to display as input boxes once the user clicks on them (the rest of the time showing as plai

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-24 09:13

    A trivial example using plain JavaScript would be along the lines of: http://jsfiddle.net/vzxW4/.

    document.getElementById('test').onclick = function() {
        document.body.removeChild(this);
        var input = document.createElement('input');
        input.id = 'test';
        input.value = this.innerHTML;
        document.body.appendChild(input);
        input.select();
    }
    

    Using a library would save you time and headaches, though. For example, using jQuery: http://jsfiddle.net/vzxW4/1/.

    $("#test").click(function() {
        var input = $("", { val: $(this).text(),
                                   type: "text" });
        $(this).replaceWith(input);
        input.select();
    });
    

提交回复
热议问题