[英]jQuery var to equal the value of the input box that it is focused on
我正在构建一个动态的小长度转换器,其中包含3个input [text] s。 像这样
<input type='text' class='bx' id='cm'> Centimeter<br>
<input type='text' class='bx' id='m'> Meter<br>
<input type='text' class='bx' id='km'> Kilometer<br>
效果如下:如果单击“仪表”,则该值变为”,如果键入一个值,则“厘米”和“公里”的值将等于一个值(...)。
jQuery就像这样:
$(function() {
var selected = ????;
// do i need something here to empty the input it is focused on?
$("#cm").val(selected * 545);
$("#km").val(selected * 545);
$("#m").val(selected * 453);
})
我希望所选的var等于它所关注的文本输入的值。
我怎样才能做到这一点?
示例中的计算是有益的。
您可以使用jQuery focus获得选定的输入字段。
$(function() {
$("input.bx").focus({
var selected =parseInt(this.value, 10);
this.value = ''; //this line will remove text from selected input.
$("#cm").val(selected * 545);
$("#km").val(selected * 545);
$("#m").val(selected * 453);
});
})
var selected = $(this).val();
// //您编写的代码仅在页面首次加载时有效。 如果希望它在每次单击时起作用,则需要处理输入的焦点事件。
$('#cm , #km , #m').on('focus', function() {
var selected = parseInt($(this).val() , 10) ; // Will convert to a Int
$("#cm").val(selected * 545);
$("#km").val(selected * 545);
$("#m").val(selected * 453);
});
但是我认为模糊事件比聚焦事件更有意义。
它将指向所选输入的值
您必须实现一个监听焦点事件的监听器。
看一下这个:
$('.bx').focus(function() {
var id = $(this).attr("id");
if (id === "cm") {
alert('Handler for .focus() called cm');
}
else if (id === "m") {
alert('Handler for .focus() called m');
}
else if (id === "km") {
alert('Handler for .focus() called km');
}
});
您需要一个事件处理程序,在这种情况下,需要focus
事件 :
$(function() {
$(".bx").focus(function(e) {
var selectedval = this.value,
selectedtype = this.id;
…
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.