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

如何用jQuery实现仅当headerTxt参数有值时动态创建对应标签

Conditionally Add First

Problem Description

I have this jQuery-based function CreateInputCheckboxActive for building HTML checkboxes:

CreateInputCheckboxActive: function (id, mainClass, checked, headerTxt, inputTxt) { 
    var bootstrapClass = "col-sm-6 "; 
    return ( 
        $("<div/>", { class: bootstrapClass + mainClass }).append( 
            $("<label/>", { "text": headerTxt }), 
            $("<input/>", { "id": mainClass, "class": mainClass, "type": "checkbox", "checked": checked }), 
            $("<label/>", { "class": mainClass, "for": mainClass, "text": checked == true ? inputTxt[0] : inputTxt[1] }) 
        ) 
    ); 
}

I want to modify it so that the first <label> element is only created when headerTxt has a valid value (like non-empty, not undefined), while keeping the current jQuery syntax. How can I do this?


Solution

Hey, this is a straightforward tweak! We can handle this in two clean ways while sticking to your existing jQuery pattern:

Approach 1: Collect Elements in an Array (Most Readable)

This method uses an array to gather elements we want to append, adding the header label only if headerTxt is valid. jQuery's append() method happily accepts an array of elements, making this super clean:

CreateInputCheckboxActive: function (id, mainClass, checked, headerTxt, inputTxt) { 
    var bootstrapClass = "col-sm-6 "; 
    // Initialize an array to hold our elements
    const elements = [];

    // Add the header label ONLY if headerTxt has a valid, non-empty value
    if (headerTxt && headerTxt.trim() !== '') {
        elements.push($("<label/>", { "text": headerTxt }));
    }

    // Add the fixed input and secondary label
    elements.push(
        $("<input/>", { "id": mainClass, "class": mainClass, "type": "checkbox", "checked": checked }),
        $("<label/>", { "class": mainClass, "for": mainClass, "text": checked ? inputTxt[0] : inputTxt[1] })
    );

    // Append all elements to the container div
    return $("<div/>", { class: bootstrapClass + mainClass }).append(elements);
}

Note: Adjust the condition headerTxt && headerTxt.trim() !== '' to match your definition of "valid value" — if you need to allow whitespace or handle other edge cases, modify this check accordingly.

Approach 2: Inline Conditional in Chain (More Compact)

If you prefer a more concise chained syntax, you can use a ternary operator directly inside the first append() call. jQuery ignores null values passed to append(), so this works perfectly:

CreateInputCheckboxActive: function (id, mainClass, checked, headerTxt, inputTxt) { 
    var bootstrapClass = "col-sm-6 "; 
    return $("<div/>", { class: bootstrapClass + mainClass })
        // Conditionally append the header label
        .append(headerTxt && headerTxt.trim() !== '' ? $("<label/>", { "text": headerTxt }) : null)
        // Append the fixed input and secondary label as before
        .append(
            $("<input/>", { "id": mainClass, "class": mainClass, "type": "checkbox", "checked": checked }),
            $("<label/>", { "class": mainClass, "for": mainClass, "text": checked ? inputTxt[0] : inputTxt[1] })
        );
}

Both approaches maintain your original jQuery style and solve the problem of only adding the header label when headerTxt is valid. The array method is easier to read if you ever need to add more conditional elements later!


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:09:46