我的页面上有2个按钮。按钮1正在执行javascript函数,另一个用于表单处理。问题是按钮1覆盖了按钮2的值和功能。
按钮1(不在表单中)具有以下HTML代码:
<input id="show_hint" class="button" type="submit" value="Hint" onClick="location.href='#hint'" />
附加的JavaScript是:
// Button 1
$(function(){
var count = 3,
$btn = $('input[type="submit"]');
$btn.val($btn.val()+' ('+count+')')
$btn.click(function(){
$btn.val($btn.val().replace(count,count-1));
count--;
$('#hintscore')
.hide()
.css({
bottom: 30,
left: 300,
opacity: 1,
})
.show()
.stop()
.delay(200)
.animate({'bottom':75, opacity: 0},1000);
if(count==0) {
return !$btn.attr('disabled','disabled');
}
})
});
按钮2(在表单中)有这个HTML代码:
<input id="showmenu_win2" class="button" type="submit" value="Menu" />
附加的JavaScript是:
$('#form').submit(function() {
$.ajax({
type: "POST",
data: $("#form").serialize(),
cache: false,
url: "insert.php"
});
return false;
});
所以这两者相互冲突,它与type =“submit”有关。但我该如何解决这个问题呢?
非常感谢
答案 0 :(得分:1)
$btn = $('input[type="submit"]');
将在DOM中选择全部提交输入元素(因此,当您调用$btn.click(...
时,基本上将此事件处理程序绑定到两个提交按钮)。
由于您在每个按钮上都有ID,因此可以更改:
$btn = $('input[type="submit"]');
要:
$btn = $('#show_hint');
您还可以找到一个根元素来启动您的选择器,以便您只选择所需的按钮:
$btn = $('#ancestor-element').find('input[type="submit"]');
或者,如果要选择除表单中的所有input[type="submit"]
元素之外的所有元素:
$btn = $('input[type="submit"]').not($('#form').find('input[type="submit"]'));
答案 1 :(得分:1)
这部分JS:
$btn = $('input[type="submit"]');
正在选择两个按钮,因此会将相同的行为附加到两个按钮。
由于每个按钮都有一个id,因此您可以通过id:
精确选择所需的按钮$btn = $("#show_hint");
答案 2 :(得分:1)
将按钮类型更改为普通输入按钮而不是提交。通过选择ID选择器
更改脚本以将按钮绑定到函数在下面的代码$("#show_hint")
中,将返回输入按钮的对象,其ID为show_hint
。
//按钮1
HTML
<input id="show_hint" class="button" type="button" value="Hint" onClick="location.href='#hint'" />
脚本
$(function(){
var count = 3,
$("#show_hint").val($(this).val()+' ('+count+')')
$("#show_hint").click(function(){
$("#show_hint").val($(this).val().replace(count,count-1));
count--
// Your remaining code...
对于第二个按钮
HTML
<input id="showmenu_win2" class="button" type="input" value="Menu" />
脚本
$('#showmenu_win2').click(function() {
$.ajax({
type: "POST",
data: $("#form").serialize(),
cache: false,
url: "insert.php"
});
return false;
});
答案 3 :(得分:0)
您可以使用常规<input type="submit">
替换<button>
。实现同样的目标。
您甚至可以使用onclick事件创建<div>
以模仿按钮。您不限于input type="submit"
答案 4 :(得分:0)
我不确定这是你想要的解决方案。我的回答是设置显示/隐藏按钮以输入=&#34;按钮&#34;提交时输入=&#34;提交&#34;。 实施例
<button id="hide" type="button" >Hide</button>
<button id="show" type="button" >Show</button>