javascript - 在模态中使用 Javascript 修改 URL
问题描述
我几乎实现了我想要实现的目标......但是缺少最后一步。一个 URL 需要由用户完成(附加一个参数),然后需要打开该 URL。
我的 HTML 中有以下可点击的链接
<a class="dropdown-item" href="#" data-href="https://www.example.com/create&r=1&q=" data-toggle="modal" data-target="#mood"><i class="fa fa-trash"></i> MOOD</a>
这会打开一个引导模式,用户可以在其中插入一个字符串来完成上面的 URL(URL+user'string)
<!-- Modal -->
<div class="modal fade" id="mood" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
Complete
</div>
<div class="modal-body">
<label for="moodUser">Enter your mood</label>
<input type="text" class="form-control" id="moodUser" aria-describedby="moodHelp" placeholder="Enter mood">
<small id="moodHelp" class="form-text text-muted">info .</small>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<a class="btn btn-danger btn-ok">Complete</a>
</div>
</div>
</div>
这里是打开模态并传递 HREF 的 Javascript
$('#mood').on('show.bs.modal', function(e) {
$(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
});
现在,当用户点击“完成”时,如何将 id="mood" 的内容添加到我的 url?
解决方案
这是您如何处理Complete
按钮单击的方法。
为了让事情更简洁,让我们首先为我们正在使用的元素提供 id,并将 Complete 锚点更改为一个按钮:
<a id="mood-anchor" class="dropdown-item" href="#"
data-href="https://www.example.com/create&r=1&q=" data-toggle="modal"
data-target="#mood"><i class="fa fa-trash"></i> MOOD</a>
<!-- ... -->
<button id="ok-btn" class="btn btn-danger btn-ok">Complete</btn>
$('#mood').on('show.bs.modal', function(e) {
$(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
// set up the 'Complete' button handler
const okbutton = document.getElementById('ok-btn');
okbutton.onclick = function () {
// get value of user-entered data
const inputVal = document.getElementById('moodUser').value;
const atag = document.getElementById('mood-anchor');
// append it to the anchor tag's 'data-href'
atag.dataset.href += inputVal;
// hide the modal
$('#mood').modal('hide');
};
});
推荐阅读
- javascript - Javascript数组 - 内存中数组的实际结构?
- java - 在 Java Swing 中可以同时进行行选择和单元选择吗?
- angular - 角度:至少一个路由解析器没有发出任何值,因此页面不会一直加载
- reactjs - 如何使用 useState 更新数组元素
- google-apps-script - 在非工作时间将自动回复的电子邮件标记为特定标签
- java - 使用反向传播的多层神经网络的准确度在 86% 左右正常吗?
- python - 守护程序中的ffmpeg错误
- adsense - 为什么我的 google adsense 广告会在检查控制台中创建错误?
- c# - 使用 EF 和 SQLite 的 AddOrUpdate 语法
- server - 在服务器上安全地运行用户提供的纯函数