JQuery.replaceWith()突然将新元素放错了位置

JQuery .replaceWith() suddenly putting new element in the wrong place?

本文关键字:元素 错了 位置 replaceWith 突然 JQuery 新元素      更新时间:2023-09-26

这个真的让我很困惑。我用replaceWith()来"清除"一个文件输入字段。然而,当它取代它时,它把它放回了错误的地方,我不知道为什么。我在标题中使用了"突然"一词,因为更神秘的是,当我周末停止工作时,接替我的人正按预期工作。现在我又开始工作了,但突然间就没有了。

以下是调用replaceWith():之前的源HTML

<label>Audio</label>
<i style="color:#888888;">MP3 or OGG format recommended</i>
<br>
<button id="clear_audio_input" style="display:none;">Clear</button>
<input type="file" value="" name="source_audio" style="width:300px;">
<br>
<div style="margin-top:15px;">
    <b>Current: </b>
    <i id="current_audio_source">1360954394_121RuleOfRosePianoEtudeI.mp3</i>
    <br>
    <input id="source_audio_value" class="required_media" type="hidden" value="1360954394_121RuleOfRosePianoEtudeI.mp3" name="source_audio">
    <span id="current_audio_info_a"><input type="checkbox" style="position:relative;top:3px;margin-left:0px;" value="yes" name="source_audio_delete">

是否删除当前音频?当前音频将被替换

请注意FILE输入字段的位置,该字段名为"source_audio"。它紧跟在"清除"按钮之后。

现在,在我调用replaceWith()之后,HTML看起来像这样:

<label>Audio</label>
<i style="color:#888888;">MP3 or OGG format recommended</i>
<br>
<button id="clear_audio_input" style="display: none;">Clear</button>
<br>
<div style="margin-top:15px;">
    <b>Current: </b>
    <i id="current_audio_source">1360954394_121RuleOfRosePianoEtudeI.mp3</i>
    <br>
    <input type="file" value="" name="source_audio" style="width:300px;">
    <input id="source_audio_value" class="required_media" type="hidden" value="1360954394_121RuleOfRosePianoEtudeI.mp3" name="source_audio">
    <span id="current_audio_info_a" style="display: inline;"><input type="checkbox" style="position:relative;top:3px;margin-left:0px;" value="yes" name="source_audio_delete">

是否删除当前音频?当前音频将被替换

请注意,它现在在另一个DIV.中有几行

以下是控制"清除"按钮操作的脚本:

$("#clear_audio_input").live("click", function() {
    $("input[name='source_audio']").replaceWith($("input[name='source_audio']").val('').clone(true));
    $("#source_audio_value").val($("#current_audio_source").text());
    $(this).hide();
    $("#current_audio_info_a").show();
    $("#current_audio_info_b").hide();
    checkRequiredMedia();
    return false;
});

以下是基本的预期工作流程。加载时,清除按钮被隐藏,因为没有任何内容需要清除。用户选择文件后,会出现清除按钮。单击该按钮将清除文件输入(通过替换它),然后该按钮将再次隐藏,基本上将表单恢复到加载时的状态。

为什么会发生这种奇怪的事情(尤其是几天前没有发生,从那以后我什么都没改变)?

问题是因为您有两个名称为source_audio的输入。为了解决这个问题,您需要为这两个输入字段指定一个id,或者更改名称。

例如:

$('#my_file_input').replaceWith('<input id="my_file_input" type="file" name="source_audio" />');
$('#my_hidden_file_input').val('');