简体   繁体   English

根据按钮单击更改模态的href

[英]Change href of modal based on button click

Clicking this button opens the modal 单击此按钮可打开模态

<button type="button" id ="soldBtn" class="btn btn-info" data-toggle="modal" data-target="#myModal">This laptop has been sold</button>

This is the modal 这是模式

<div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog modal-sm">
      <div class="modal-content">
        <div class="modal-header">
          <p>Confirmation</p>
        </div>
        <div class="modal-body">
          <p>Are you sure you want to do this?</p>
        </div>
        <div class="modal-footer">
          <a class="btn btn-outline-success" id="confirmBtn" href="#" >Yes</a>
            <a class="btn btn-outline-danger" id="cancelBtn" data-dismiss="modal">No</a>
        </div>
      </div>
    </div>
  </div>
</div>

I could just have a different modal for different buttons, but I'd rather follow the DRY principle. 我可以为不同的按钮设置不同的模态,但我宁愿遵循DRY原则。 I'd like the href of the confirmBtn to change based on which button to open the modal was clicked. 我希望confirmBtnhref根据点击打开模态的按钮进行更改。 I've tried this so far but not even sure if I'm on the right track. 到目前为止我已经尝试过这个但是我甚至不确定我是否在正确的轨道上。

<script type="text/javascript">
  if(jQuery('#soldBtn').data('clicked')) {
    document.getElementById("confirmBtn").href="{%url 'laptops:sale'%}";
}
</script>

You should first wait for your DOM to load. 您应该先等待DOM加载。 This can be done by wrapping your script code with the following: 这可以通过使用以下内容包装脚本代码来完成:

$(function(){
    // Here you will place the code that follows
});

Then you should register an event handler for the click event on the DOM element with id soldBtn : 然后,您应该在id为soldBtn的DOM元素上为click事件注册一个事件处理程序:

$("#soldBtn").on('click', function(){
    var confirmBtnEle = $("#confirmBtn");
    confirmBtnEle.attr('href','%url 'laptops:sale'%');
});

Apparently, you have to change the second argument we pass to attr method above to be that you want to be. 显然,您必须将我们传递给上面的attr方法的第二个参数更改为您想要的。

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

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