当我单击我添加的几个新按钮时,正在发生一些奇怪的事情。他们的工作正常,但是他们不断将页面滚回到屏幕顶部。我认为我的代码中的其他事情正在引起它,因为我确实在其他地方具有这种行为,但是我无法弄清楚什么正在干扰(此时我的代码非常大)。
单击按钮时,最简单的方法是什么?我知道F12调试器的基础知识,但是除此之外,我有点毫无疑问。我已经阅读了有关事件手的人等,但从未使用过,因此希望有一种更简单的方法来追踪它。
这是按钮代码。看起来还不错,它可以做应该做的事情,但也具有不必要的行为。
$(document).on('click', '.friendly_submit', function () {
// Work out our team ID.
var OurTeamIDF = $('div').find('[data-ourteamid]');
var OurTeamID = OurTeamIDF.data('ourteamid');
var OpponentID = $(this).closest('form')
.find('.friendly_opponent')
.find(':selected').attr('data-OpponentID');
var Venue = $(this).closest('form')
.find('.friendly_venue')
.find(':selected').text();
var WhichFriendly = $(this).closest('form').attr('data-WhichFriendly');
$.post('scripts/randomfriendly.php',
{
OurTeamID : OurTeamID,
OpponentID : OpponentID,
Venue : Venue,
WhichFriendly : WhichFriendly
},
function (data) {
console.log(data);
}
)
});
,HTML代码如下。
echo "<form data-WhichFriendly = 0 class = 'box_center center'>";
echo "<fieldset class = 'random_friendly_fieldset box_center'>";
echo "<legend>Random Friendly</legend>";
//echo "<p class = 'bold center underline'>Choose Opponent</p>";
echo "Choose Opponent : <select class = 'friendly_opponent'>";
foreach ($AllTeamsArray as $Team) {
// Don't include ourselves in the list.
if (trim($Team['Name']) <> trim($OurTeamName)) {
$TeamID = $Team['ID'];
echo "<option data-OpponentID = $TeamID>" . $Team['Name'] . " (" . $Team['League'] . ")</option>";
}
}
echo "</select></br></br>";
echo "Venue : <select class = 'friendly_venue'>";
echo "<option>Neutral</option>";
echo "<option>Home</option>";
echo "<option>Away</option>";
echo "</select></br></br>";
echo "<button class = 'friendly_submit'>Submit</button>";
echo "</fieldset>";
echo "</form>";
有两件事跳到我心中:
1)按钮是type="submit"
,并且正在提交表单(这会导致页面刷新)
2)按钮是设置为href="#'
编辑
现在您已经发布了代码,我正在更新我的答案。
更改您的代码,以便您不要在按钮上捕获单击事件,而是在表格上捕获提交事件。
$( "#add-form-id-here" ).submit(function( event ) {
event.preventDefault();
//change your handler so you get the correct values etc here.
});
然后确保将type="submit"
添加到按钮。
尝试添加以下内容:
event.preventdefault();
event.stoppropagation();
$(document).on('click', '.friendly_submit',
function () {
// Work out our team ID.
var OurTeamIDF = $('div').find('[data-ourteamid]');
var OurTeamID = OurTeamIDF.data('ourteamid');
var OpponentID = $(this).closest('form').find('.friendly_opponent').find(':selected').attr('data-OpponentID');
var Venue = $(this).closest('form').find('.friendly_venue').find(':selected').text();
var WhichFriendly = $(this).closest('form').attr('data-WhichFriendly');
event.preventDefault();
event.stopPropagation();
$.post('scripts/randomfriendly.php',
{
OurTeamID : OurTeamID,
OpponentID : OpponentID,
Venue : Venue,
WhichFriendly : WhichFriendly
} ,
function (data) {
console.log(data);
})
});