Building HTML Elements with Readability and Maintenance

When repeating some cell data, I create an array of the found. The first iteration simply wraps the found text in the <span> tags, while the subsequent iterations add a bunch of other styles, as shown below:

 var array = $('table').find('th').map(function(i){ if (i===0){ // This bit 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(); 

Everything works fine, but it's disgusting - and I think I saw a much more elegant way to create HTML elements with styles somewhere earlier.

Could someone suggest a more “service-friendly” way of writing else ?

EDIT . Using CSS classes is not really a solution, as the code applies values ​​based on other calculations.

+4
source share
2 answers

As suggested in the comments, consider storing the values ​​that are used for all elements of the CSS class, in this example I will choose .something .

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

Further, in jQuery you can save a copy of your span element in a variable, as you are going to use it in both cases. In the else block, you can simply apply the class and add individual styles.

EDIT . You can simplify the code even further. You will return the range that will happen, so you only need to check if i 0 does not match.

 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(); 
+4
source

How about something more?

 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(); 
0
source

Source: https://habr.com/ru/post/1480936/


All Articles