我正在使用 Jquery 刷新页面,它正在刷新,但是当我从类别中选择一个选项时,它会刷新,然后我选择的类别消失,但我希望当我选择任何一个选项时,页面都会刷新,但我选择的选项也将与我选择的相同,希望你们能理解我的问题。
$(function() { $('select[name="cat"]').change(function() { location.href = 'insert_book.php?cat=' + $(this).find('option:selected').val(); }); });
<select id="rf" name="cat">
<option value='null'>Select your Desire</option>
<?php
include('includes/db.php');
$c_query="select * from categories";
$c_run=(mysql_query($c_query));
while($c_row=mysql_fetch_array($c_run)){
$c_id=$c_row['p_id'];
$c_title=$c_row['p_title'];
echo "<option value='$c_id'>$c_title</option>";
}
?>
</select>
最佳答案
将刷新代码更改为:
$(function() { $('select[name="cat"]').change(function(ev) { location.href = 'insert_book.php?cat=' + $(ev.currentTarget).val(); }); });
Also move this JS code after the HTML code for the select
element or wrap it with $(document).ready()
like this:
$(document).ready(function(){ $('select[name="cat"]').change(function(ev) { location.href = 'insert_book.php?cat=' + $(ev.currentTarget).val(); }); });
Now in the loop code:
$selectedCategory = array_key_exists('cat', $_GET) ? $_GET['cat'] : 0;
while($c_row=mysql_fetch_array($c_run)){
$c_id=$c_row['p_id'];
$c_title=$c_row['p_title'];
echo "<option value='$c_id'".($selectedCategory == $c_id ? " selected='selected'" :"").">$c_title</option>";
}
最后:
正如 Chris Baker 提到的,停止使用 mysql_ 并使用 mysqli_ 或 PDO。
关于javascript - 使用JQuery刷新页面但没有得到想要的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26916874/