【问题标题】:When dynamically creating HTML elements with jQuery, how to include values conditionally in the JSON?使用 jQuery 动态创建 HTML 元素时,如何有条件地在 JSON 中包含值?
【发布时间】:2012-02-05 01:53:56
【问题描述】:

我正在为 XML 文件中的每个项目创建一个复选框。每个文件的文本是"TRUE""FALSE",我想为每个"TRUE" 创建一个选中的复选框,为每个"FALSE" 创建一个未选中的复选框。现在我的代码在 if 和 else 中重复,因为我想不出有条件地在该 JSON 中包含已检查参数的方法。有谁知道完成同样事情的更干燥的方法?

d = $(this)
if (d.text() === 'TRUE') {
    $('<input>', {
    className: 'checkbox',
    type: 'checkbox',
    id: d.attr('id'),
    name: d.attr('name'),
    checked: 'checked'
    }).appendTo(td);
}
else {
    $('<input>', {
    className: 'checkbox',
    type: 'checkbox',
    id: d.attr('id'),
    name: d.attr('name')
    }).appendTo(td);
}

【问题讨论】:

  • 如果符合您的要求,请尝试使用 .serialize()。

标签: jquery xml json checkbox


【解决方案1】:

你也可以这样做:

var d = $(this);
var options = {
        className: 'checkbox',
        type: 'checkbox',
        id: d.attr('id'),
        name: d.attr('name')
    };
options.checked = d.text() === 'TRUE' ? 'checked' : '';
/* --or if you think this is more readable
 *if (d.text() === 'TRUE') {
 *  options.checked = 'checked';
 *}
*/
$('<input>', options).appendTo(td);

没有规定不能提前构建属性映射的“规则”。 :)

【讨论】:

  • 谢谢——这是关键。三元组不起作用,因为如果选中的属性完全存在,它将返回选中。 if 语句有效并且是 DRY。
【解决方案2】:
var d = $(this),
    $input = $('<input>', {
        className: 'checkbox',
        type: 'checkbox',
        id: d.attr('id'),
        name: d.attr('name')
    }).appendTo(td);

if(d.text() === 'TRUE') $input.prop('checked', true);

【讨论】:

  • 那行不通。如果checked 属性存在,它将返回checked。
  • @MichaelHopkins 根据您的建议更新了答案
猜你喜欢
  • 2014-04-16
  • 1970-01-01
  • 2015-11-05
  • 1970-01-01
  • 2020-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多