简体   繁体   English

为什么我的jQuery不更新DOM?

[英]Why isn't my jQuery updating the DOM?

Ok, so I'm making a login screen for an application with a button that says "Not You?" 好的,所以我正在为一个应用程序创建一个登录屏幕,其中有一个按钮,上面写着“不是吗?” which, when clicked, brings up a text-box to update the username on the screen. 单击时,会弹出一个文本框来更新屏幕上的用户名。 The issue I'm having is: the username updates once, but when tried again doesn't work. 我遇到的问题是:用户名更新一次,但再次尝试时不起作用。 What's wrong with my jQuery? 我的jQuery有什么问题?

Here's my jQuery: 这是我的jQuery:

var main = function(){
$('.not').click(function(){
    $('.login-wrap').fadeOut(300, function(){
        $('.not-you').fadeIn(300); 
    });
});

$('.enter').click(function(){
    $('.name').replaceWith($('.new-input').val());
    $('.not-you').fadeOut(300, function(){
        $('.login-wrap').fadeIn(300);
    });
  });
}

$(document).ready(main);

And HERE'S a link to the CodePen. 这里是CodePen的链接。

Thanks! 谢谢!

From the docs , The .replaceWith() method removes content from the DOM and inserts new content in its place with a single call,so for first time it is working fine but when first time .replaceWith() is used it replaces whole '.new-input' with class 'name' ,that is why afterwards it is creates problems. 文档中.replaceWith()方法从DOM中删除内容并通过一次调用在其位置插入新内容,因此第一次它正常工作但是当第一次使用.replaceWith()它会替换整个'.new-input' input'with class'name 'name' ,这就是为什么之后它会产生问题。

Instead of 代替

$('.name').replaceWith($('.new-input').val());

Try 尝试

$('.name').html($('.new-input').val());

OR 要么

$('.name').text($('.new-input').val());

see here. 看这里。

When you are doing replaceWith(), you are actually removing the whole tag with class '.name'. 在执行replaceWith()时,实际上是使用类“.name”删除整个标记。 So in the next time the code is unable to find any object with class 'name'. 因此,在下一次代码无法找到具有类“name”的任何对象时。

Use '.html()' to make it work. 使用'.html()'使其工作。

You can change your replaceWith() line with the following: 您可以使用以下内容更改replaceWith()行:

$('.name').replaceWith("<span class='name'>"+$('.new-input').val()+"</span>");

replaceWith() actually replaces the whole DOM element that has the class of name . replaceWith()实际上替换了具有name类的整个DOM元素。

.replaceWith() | .replaceWith()| jQuery API Documentation jQuery API文档

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

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