【问题标题】:pass variable to quotation in javascript在javascript中将变量传递给引号
【发布时间】:2021-12-20 14:11:01
【问题描述】:

我有一个网络应用,后端使用 Django,前端使用 HTML5。

我想将一个变量从引导表传递给 javascript 中的引用。

<th class ='Format_issued' data-field="book.publisher" data-formatter="renderFormat">Material Format</th>

<script>
            function renderFormat(value) {
            return '<select style="width: 7em" name="Material_format" id="Material_format" >\n' +
                '                <option value="">--Select--</option>\n' +
                '               <option value="eText" {% if ' + value + ' == "eText"  %} selected="selected" {% endif %}>eText</option>\n' +
                '                <option value="No Material" {% if value == "No Material"  %} selected="selected" {% endif %}>No Material</option>\n' +
                '              
                '            </select>'
        }
</script>

'value' 是我要传递的变量。 但我尝试了几种方法: 1.使用'+值+':' &lt;option value="eText" {% if ' + value + ' == "eText" %} selected="selected" {% endif %}&gt;eText&lt;/option&gt;\n'

2 。直接在我的js引用中使用值:'&lt;option value="No Material" {% if value == "No Material" %} selected="selected" {% endif %}&gt;No Material&lt;/option&gt;\n'

all 无法传递 value 变量。

我如何传递“价值”?

【问题讨论】:

标签: javascript django


【解决方案1】:

在处理一些复杂的字符串输出时总是使用 javascript 模板字面量。 在您的情况下,可以将模板文字与 JS 三元运算符结合起来,如下所示:

function renderFormat(value) {
    return `<select style="width: 7em" name="Material_format" id="Material_format">
    <option value="" ${(value === 'empty') ? 'selected="selected"' : ""}>--Select--</option>
    <option value="eText" ${(value === 'eText') ? 'selected="selected"' : ""}>eText</option>
    <option value="No Material" ${(value === 'No Material') ? 'selected="selected"' : ""}>No Material</option>
</select>`;

}

测试输出:

console.log(renderFormat("No Material"));
// console.log(renderFormat("eText"));
// console.log(renderFormat("empty"));

// Output
<select style="width: 7em" name="Material_format" id="Material_format">
  <option value="" >--Select--</option>
  <option value="eText" >eText</option>
  <option value="No Material" selected="selected">No Material</option>
</select>

注意: 不要混用 Js 模板文字和 Django 模板标签。只是一个建议。

更多关于javascript ternary operatorJavaScript template literals

【讨论】:

    猜你喜欢
    • 2013-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 2018-09-23
    • 2012-01-28
    相关资源
    最近更新 更多