Javascript 在jquery中插入文本

Javascript 在jquery中插入文本,javascript,jquery,dom,Javascript,Jquery,Dom,这是个问题。 我现在想在输入之前插入文本。这就是我所做的 $(document).on('click','#phoneDiv',function(){ phone=$("#editPhone").val(); $("#phoneDiv").contents().filter(function() { return (!$(this).is(".editmode")); }).remove(); $('div#editPhone').prepend(

这是个问题。 我现在想在输入之前插入文本。这就是我所做的

$(document).on('click','#phoneDiv',function(){
    phone=$("#editPhone").val();
    $("#phoneDiv").contents().filter(function() {
        return (!$(this).is(".editmode"));
    }).remove();
    $('div#editPhone').prepend(document.createTextNode(phone));
});

这里当然是。它只删除文本,但不插入值。

这是因为您正在删除
phonediv
内容。因此,当您尝试对其进行预编译时,
div#editPhone
(phonediv的子项)不存在

$(document).on('click','#phoneDiv',function(){
    var phone=$("#editPhone").val();
    $("#phoneDiv").contents().filter(function() {
        return (!$(this).is(".editmode"));
    }).remove();
    $('div#phoneDiv').prepend(phone); //<-- div#editPhone doesn't exist anymore, you removed it above
});
$(文档).on('click','phoneDiv',function(){
var phone=$(“#editPhone”).val();
$(“#phoneDiv”).contents().filter(函数(){
返回(!$(this).is(“.editmode”);
}).remove();

$('div#phoneDiv')。前置(电话)//有没有任何理由把
jQuery
Vanilla Javascript
混为一谈?我建议你选择一个并坚持到底。要扩展@MelanciaUK的观点,为DOM操作选择一个并坚持到底。在声明变量时使用
var
,除非你在代码中的其他地方全局声明了它。实际上,你不会这样做使用
.filter()
.contents()
需要所有代码。一个简单的
.children()
就可以了。在
单击事件处理程序中,您可以通过
$(this)
引用
$(“#phoneDiv”)