【发布时间】:2021-11-01 17:17:51
【问题描述】:
我是 javascript 新手,想根据按钮标签或名称打开多个不同的模式。
我正在执行 ajax 调用,然后将根据按钮标签/名称打开一个模式。
如果有人能指出我正确的方向,那就太好了。下面是我目前使用的,它适用于一种模式,但不适合不同的模式 id。任何帮助将不胜感激。
//form button script
<form action="https://test.com/testme.html" method="post" class="ajax">
<button class="item" id="test1" name="testing" value="1" data-toggle="tooltip" data-placement="top" type="submit" title="" data-original-title="test1">
</button>
</form>
//javascript
<script>
$(document).ready(function() {
$('form.ajax').on('submit', function(event) {
event.preventDefault();
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
// AJAX request
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
// Add response in Modal body
$('.modal-body').html(response);
// Display Modal
$('#MyModal').modal('show');//want #MyModal to be var button id test1 so $('#test1').modal('show')
}
});
});
});
</script>
【问题讨论】:
-
您可以在选择器中使用模板文字。
const buttonId = 'test1'; $(`#${buttonId }`).modal('show');更多:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… -
欢迎来到 Stack Overflow。 HTML ID 必须是唯一的。这意味着您已经有一个 ID 为
test1的 Button;因此,您不能(嗯,不应该)拥有具有相同 ID 的模态 DIV。 -
感谢 Twisty,你当然是对的。我已经修改了按钮名称。关于如何处理这个问题的任何更好的选择将不胜感激。谢谢你的时间。我也会试试史蒂夫的选择。
标签: javascript html jquery ajax