dap*_*hez 1 javascript ajax jquery onchange radio-button
我有一个显示记录列表的页面.用户可以使用单选按钮选择记录状态,例如:
<div id="record_653">
<label><input type="radio" name="status_653" value="new" checked/>new</label>
<label><input type="radio" name="status_653" value="skipped" />skipped</label>
<label><input type="radio" name="status_653" value="downloaded" />downloaded</label>
</div>
Run Code Online (Sandbox Code Playgroud)
我正在使用JQuery将用户所做的更改发送回服务器,在那里我使用它们来更新数据库.这是我所做的简化版本:
$("#record_653").click(
function(event) {
var url = ...,
params = ...;
post(url,params);
});
Run Code Online (Sandbox Code Playgroud)
问题是,即使用户单击先前检查过的相同按钮,此代码也会创建请求.我真正想要的是"on change"事件,除了它在Internet Explorer中的行为不是很有用(例如这里).
所以我想我不知何故必须确定click事件是否改变了值.
旧值是存储在某个地方(在事件中的DOM?中)所以我可以比较它?
如果没有,我应该如何存储旧值?
旧值不会存储在您可以查询的位置,不会.您需要自己存储值.您可以使用javascript变量,隐藏input元素或jQuery data()函数.
编辑
jQuery data函数提供对键 - 值对数据结构的访问,作为存储给定元素的任意数据的方法.api看起来像:
// store original value for an element
$(selector).data('key', value);
// retrieve original value for an element
var value = $(selector).data('key');
Run Code Online (Sandbox Code Playgroud)
一个更发达的想法:
$(document).ready(function() {
// store original values on document ready
$(selector).each(function() {
var value = $(this).val();
$(this).data('original-value', value);
})
// later on, you might attach a click handler to the the option
// and want to determine if the value has actually changed or not.
$(selector).click(function() {
var currentValue = $(this).val();
var originalValue = $(this).data('original-value');
if (currentValue != originalValue) {
// do stuff.
// you might want to update the original value so future changes
// can be detected:
$(this).data('original-value', currentValue);
}
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22778 次 |
| 最近记录: |