4

When iterating over some table cell data, I construct an array of whatever's found. The first iteration simply wraps the found text in some <span> tags, whilst the subsequent ones add a bunch of other styles, as below:

var array = $('table').find('th').map(function(i){
    if (i===0){
        // This bit's OK
        return '<span>' + $(this).text() + '</span>';
    } else {
        // This just looks horrible
        return '<span style="width:' + $(this).outerWidth() + 'px; display:inline-block; position:absolute; right:' + w[i-1] + 'px">' + $(this).text() + '</span>';
    }
}).get();

It all works fine, but it's hideous - and I think I've seen a much more elegant way of constructing HTML elements, with styles, somewhere before.

Can anyone suggest a more "maintenance-friendly" way of writing the else statement?

EDIT: Using CSS classes isn't really a solution, as the code applies values based on other calculations.

4

2 回答 2

4

正如评论中已经建议的那样,考虑存储用于 CSS 类中所有元素的值,我将选择.something此示例。

.something {
  position: absolute;
  display: inline-block;
}

接下来,在 jQuery 中,您可以将 span 元素的副本存储在变量中,因为您将在两种情况下都使用它。然后,您可以在该else块中简单地应用该类并添加各个样式。

编辑:您可以进一步简化代码。无论发生什么,您都会返回跨度,因此您只需检查是否i不等于 0。

var array = $('table').find('th').map(function (i){
  var span = $('<span>' + $(this).text() + '</span>');

  if (i !== 0) {
    span.addClass('something').css({
      width: $(this).outerWidth() + 'px',
      right: w[i-1] + 'px'
    });
  }

  return span;
}).get();
于 2013-05-15T12:09:29.180 回答
0

更像这样的东西怎么样?

var array = $('table').find('th').map(function(i){

    var element = $("<span></span>").text($(this).text());
    return (i === 0) ? element : element.css({"width": $(this).outerWidth() + "px"
                                               , "display": "inline-block"
                                               , "position": "absolute"
                                               , "right": w[i-1] + "px"});

}).get();
于 2013-05-15T12:13:54.103 回答