javascript - 为我的 jQuery 创建循环时遇到问题
问题描述
我有这个有效的脚本。到目前为止,它为最后一组正确更改了图像,我想把它放在我有 m=k 的循环中,但它不起作用
像
for (m = 0; m < k; ++m) {
<script>
$(function() {
var m = 1;
var resultb = $('[id^=input_]').filter(function () {
return this.id.match(/input_\d+$/); //regex for the pattern "input_ followed by a number"
}).length;
var k = resultb;
m = k;
$("#input_"+m).change(function() {
var val = $("#input_"+m+" option:selected").text();
var valval = $("#input_"+m+"option:selected").val();
var n = val.indexOf('(');
val = val.substring(0, n != -1 ? n : val.length);
var img_option='images/sample/'+val+'.jpg';
if ($("#input_"+m+" option:selected").val() > 0)
$("a.lb:first").html( "<img src="+ img_option+">");
$('a.lb:first img').css({'width' : '350px' });
$('a.lb:first img').addClass( "img-fluid" );
});
});
</script>
解决方案
您的m
值似乎是基于 1 的,因此您的循环将要从1
.
话虽如此,您根本不需要for
循环。只需选择您想要的元素:
$(function() {
const inputs = $('[id^=input_]').filter(function () {
return this.id.match(/input_\d+$/); //regex for the pattern "input_ followed by a number"
});
inputs.on('change', function() {
// I'm assuming that `#input_X` is actually a `<select>`, not an `<input>`
// You should probably adjust your naming convention to be less confusing
let text = this.options[this.selectedIndex].text;
let value = this.options[this.selectedIndex].value;
let parenthesis = text.indexOf("(");
if( parenthesis > -1) text = text.substring(0, parenthesis);
let source = `images/sample/${text}.jpg`;
if( value > 0) $("a.lb:first").html(`<img src="${source}" style="width: 350px" class="img-fluid" />`);
});
});
你会注意到我给你的变量取了更合理的名字,使用let
起来也const
更合适,而且通常把代码整理得尽可能干净和易于理解。
推荐阅读
- r - 多项回归的参考类别或类
- django-rest-framework - 如何从 unittest 重新生成 django 请求?
- sql - 如何通过UPDATE将数据从另一个表复制到空表中?
- node.js - 超级账本结构通道创建节点 SDK - 错误
- mongodb - 有什么方法可以在 mongoDB 中使用 $exists 和 $expr 吗?
- android - 如何在 Android Studio 中自动生成飞镖函数的标头注释?
- python - 修改同一类的另一个实例时实例变量更改值,Python-Tkinter
- sql - ORACLE SQL - 将两个查询和一个值相加
- javascript - 使用 d3js 污染图表
- android - Flutter - 无法更新或删除应用内购买的托管产品?