You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery:根据循环变量设置下拉框选中项

实现方法

你可以通过判断time_rate_default的布尔值,动态为对应选项添加选中属性,以下是两种推荐的实现方式:

方式一:字符串拼接动态生成属性

jQuery.each(time_rates_for_select, function(index, value){
    // 声明局部变量,避免全局污染
    var id = value[0];
    var rate = value[1];
    var name = value[2];
    var time_rate_default = value[3]; // true or false
    
    // 根据状态生成selected属性字符串
    var selectedAttr = time_rate_default ? 'selected="selected"' : '';
    $("#time-rate-select").append('<option value="'+ id +'" '+ selectedAttr +'>' + rate + ' - ' + name + '</option>');
});

方式二:jQuery DOM元素创建(更安全规范)

这种方式避免了HTML字符串拼接的潜在语法问题,可读性和可维护性更强:

jQuery.each(time_rates_for_select, function(index, value){
    const id = value[0];
    const rate = value[1];
    const name = value[2];
    const time_rate_default = value[3];

    // 创建option元素并设置值和文本
    const option = $("<option>")
        .val(id)
        .text(`${rate} - ${name}`);
    
    // 若为默认项则设置选中状态
    if (time_rate_default) {
        option.prop("selected", true);
    }
    
    $("#time-rate-select").append(option);
});

补充说明

  • 建议给变量添加var/let/const声明,避免全局变量污染,这是基础的编码规范。
  • 第二种方式利用jQuery的DOM操作API来设置属性,相比字符串拼接更不容易出错,尤其在处理复杂内容时优势更明显。

内容的提问来源于stack exchange,提问作者DaveC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 21:07:06