首页 > 解决方案 > 在模态中使用 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?

标签: javascripttwitter-bootstrap

解决方案


这是您如何处理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');
      };
    });

推荐阅读