gpt4 book ai didi

javascript - 如何在更改选择列表值时附加和删除 html 片段

转载 作者:行者123 更新时间:2023-12-03 02:27:50 31 4
gpt4 key购买 nike

我目前正在尝试使用 Jquery 根据下拉列表的值附加音频标签 html 列表。主要问题是,当选择值更改时,empty() 和append() 方法根本不会将html 注入(inject)到播放列表div 中。

HTML 初始状态:

  <select name="querySong" id="currentPlaylist">

<option value="playlist1">playlist 1</option>
<option value="playlist2">playlist 2</option>
<option value="playlist3">playlist 3</option>
</select>
<div class="playlist">

</div>

更改选择值后的 HTML(所需输出):

   <!-- playlist 1 selected in this case -->
<select name="querySong" id="currentSong">
<option value="playlist1">playlist 1</option>
<option value="playlist2">playlist 2</option>
<option value="playlist3">playlist 3</option>
</select>
<div class="playlist">
<p> song 1
<audio controls>
<source src="music/song1.mp3" type="audio/mpeg">
</audio>
</p>
<p> song 2
<audio controls>
<source src="music/song2.mp3" type="audio/mpeg">
</audio>
</p>
</div>

当前使用的Jquery:

$(document).on('change','#currentPlaylist',  function(e){
// e.preventDefault();
if($(this).find("option:selected").attr('value') == "song1") {

// now load correct Playlist

var playlist1 = [
'<p> song 1',
' <audio controls>',
' <source src="music/song1.mp3" type="audio/mpeg">',
'</audio>',
'</p>',
'<p> song 2',
'<audio controls>',
'<source src="music/song2.mp3" type="audio/mpeg">',
'</audio>',
'</p>',
].join("\n");

$(".playlist").empty().append(playlist1);
}
else if (
... continued logic for other select values

});

最佳答案

“song1”不是您的 #currentPlaylist 选择的选项值。

我改变了它,看起来你的代码工作得很好。

$(document).on('change','#currentPlaylist',  function(e) {
// e.preventDefault();

if($(this).find("option:selected").attr('value') == "playlist2") {
// now load correct Playlist

var playlist1 = [
'<p> song 2.1',
' <audio controls>',
' <source src="music/song1.mp3" type="audio/mpeg">',
'</audio>',
'</p>',
'<p> song 2.2',
'<audio controls>',
'<source src="music/song2.mp3" type="audio/mpeg">',
'</audio>',
'</p>',
].join("\n");

$(".playlist").empty().append(playlist1);
}

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="querySong" id="currentPlaylist">

<option value="playlist1">playlist 1</option>
<option value="playlist2">playlist 2</option>
<option value="playlist3">playlist 3</option>
</select>

<div class="playlist">
<p> song 1
<audio controls>
<source src="music/song1.mp3" type="audio/mpeg">
</audio>
</p>
<p> song 2
<audio controls>
<source src="music/song2.mp3" type="audio/mpeg">
</audio>
</p>
</div>

关于javascript - 如何在更改选择列表值时附加和删除 html 片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48864558/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com