Javascript 如何从span和bind更改事件中选择子div中的上一个输入元素?
所讨论的HTML结构如下所示:Javascript 如何从span和bind更改事件中选择子div中的上一个输入元素?,javascript,jquery,html,css,Javascript,Jquery,Html,Css,所讨论的HTML结构如下所示: <div class="form-group form-text"> <div class="input-group"> <span class="input-group-btn"> <div id="47" class="btn btn-danger input-xs remove-farming-action"> <span class="glyphicon glyp
<div class="form-group form-text">
<div class="input-group">
<span class="input-group-btn">
<div id="47" class="btn btn-danger input-xs remove-farming-action">
<span class="glyphicon glyphicon-remove"></span>
</div>
</span>
<input id="action_CropCount"
class="form-control input-xs numeric-text-box crop-counter-textbox"
type="number"
value="8"
name="action.CropCount"
min="1"
max="999">
</div>
Aubergine Violetta lunga 3
<span class="crop-count-crop-word">crop(s)</span>
<br>
</div>
(... And so on for different items.)
makeCropPluralWhenCropCountIsBiggerThan1: function() {
// Every crop count input field needs a span label with crop or crops depending on the count.
$('.crop-count-crop-word').prev('input').change(function() {
$(this).next('span').text( $(this).val() == 1 ? 'crop' : 'crops' );
});
// Ensure text is correct on load by triggering change event.
$('.crop-count-crop-word').prev('input').trigger('change');
}
不幸的是,这不起作用。我无法从span元素中选择上一个输入字段。未选择任何项目
谁能告诉我如何从“裁剪计数器文本框”类的输入中选择下一个“裁剪计数裁剪词”范围
/编辑这里是一把小提琴:您可以直接选择它:
$(".crop-counter-textbox").change(function(e){});
还是从你的跨度
$('span.crop-count-crop-word').prev(".input-group").find("input.crop-counter-textbox").change(function(e){});
.prev选择在同一级别,但在同一级别有一个div.input-group而不是您的input.crop-counter-texbox,这就是为什么您的选择器找不到它。您试图选择上一个
input
元素,但实际上有一个div
元素,其中包含input
。因此,您需要将$('.crop count crop word').prev('input')
更改为$('.crop count crop word').prev('input group').find('input')
编辑代码():
}谢谢!我如何从输入组得到跨度?
$(this.next('span').text($(this.val()==1?'crop':'crops')代码>零件?从输入中选择跨度元素不起作用。但是文本没有改变。@Erwin Rooijakkers我已经编辑了我的答案,你的提琴也能用了。只有最后一个$input.trigger('change')
应该低两行。非常感谢您的帮助。如果直接选择,您的意思是我可以使用e
变量查找范围字段?否,“e”变量是“更改”事件处理程序上的“事件”参数。通过直接选择它,我的意思是从整个DOM中选择:$(“.crop counter textbox”),而不选择上下文。在jquery中,您可以在整个文档中使用.find()从一个内部div中进行选择。哦,请注意,您有一个触发“change”事件的“change”处理程序,它看起来像一个无限递归。我想它只被调用一次。我已经实现了@TimOsadchiy的解决方案,只有在更改触发器向下两行的情况下(在更改事件之外)。
function makeCropPluralWhenCropCountIsBiggerThan1() {
// Every crop count input field needs a span label with crop or crops depending on the count.
$('.form-group').each(function() {
var $input = $(this).find('input:first');
var $span = $(this).find('.crop-count-crop-word:first');
$input.change(function() {
$span.text( $(this).val() == 1 ? 'crop' : 'crops' );
$input.trigger('change');
});
});