简体   繁体   English

如何使用 JQuery 替换 div 的内容而不是附加值?

[英]How can I replace the content of a div instead append a value using JQuery?

I am pretty new in JQuery and I have the following problem.我在 JQuery 中很新,我有以下问题。

I have create this JQuery function that when the user select a file into an input tag having id=rendicontoAllegato it put the name of this file into an hidden div having id=nomeDocumentoRendicontazione into my page我创建了这个 JQuery 函数,当用户选择一个文件到一个具有id=rendicontoAllegato的输入标签时,它会将这个文件的名称放入一个id=nomeDocumentoRendicontazione的隐藏 div 到我的页面中

$(document).ready(function() {

    $("#rendicontoAllegato").change(function() {
        alert("DOCUMENTO dopo selezione: " + $("#nomeDocumentoRendicontazione").text());

        var selectedFileName = $("#rendicontoAllegato").val();

        $('#nomeDocumentoRendicontazione').append(selectedFileName);

    });
 });

It works fine but the only problem is that if I first select something as file1.txt and then select another file as file2.txt into the div having id=nomeDocumentoRendicontazione I will have the concatenation of the 2 files name.它工作正常,但唯一的问题是,如果我首先选择某个文件作为file1.txt ,然后将另一个文件作为file2.txt选择到具有id=nomeDocumentoRendicontazione的 div 中,我将连接两个文件名。

So I will have something like file1.txtfile2.txt and it is not good for me.所以我会有类似file1.txtfile2.txt 的东西,这对我不利

How can I replace the value of the div having id=nomeDocumentoRendicontazione instead to append a new value inside it?如何替换具有id=nomeDocumentoRendicontazione的 div 的值以在其中附加一个新值?

You can use the .text() fn if you are dealing with with your data to be inserted as text or .html() fn if you are dealing with html to be replaced如果您正在处理要作为文本插入的数据,则可以使用.text() fn,如果您正在处理要替换的 html,则可以使用.html() fn

$('#nomeDocumentoRendicontazione').text(selectedFileName);

Or或者

$('#nomeDocumentoRendicontazione').html(selectedFileName);

Use html() instead of append().使用 html() 而不是 append()。

$(document).ready(function() {

    $("#rendicontoAllegato").change(function() {
        alert("DOCUMENTO dopo selezione: " + $("#nomeDocumentoRendicontazione").text());

        var selectedFileName = $("#rendicontoAllegato").val();

        $('#nomeDocumentoRendicontazione').html(selectedFileName);

    });
 });

You have to use你必须使用

 $('#nomeDocumentoRendicontazione').html(selectedFileName);

it will replace the already present HTML of that.它将替换已经存在的 HTML。 OR you can use或者你可以使用

 $('#nomeDocumentoRendicontazione').text(selectedFileName);

it will do the same but append your data as text.它会做同样的事情,但将您的数据附加为文本。

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

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