String中HTML的替代方案

时间:2017-01-17 07:51:18

标签: javascript html

我现在正在使用此代码,但我并不喜欢它的外观。

function createPageSettingsPopup(page) {
  return '<div class="form-group">' +
    '<label for="page-title">Title</label>' +
    '<input type="text" class="form-control" id="page-title" value="' + page.title + '">' +
    '</div>'
}

有没有其他方法可以在字符串中编写HTML以使其看起来更好?

4 个答案:

答案 0 :(得分:4)

您可以使用模板引擎。这是以牺牲页面中的元素为代价的,但代码看起来更清晰,模板更容易理解为HTML。将模板放在脚本标记中,type设置为text/template

<script type="text/template" id="tmpl">
    <div class="form-group">
        <label for="page-title">Title</label>
        <input type="text" class="form-control" id="page-title" value="{{pageTitle}}">
    </div>
</script>

并修改您的功能如下。请记住缓存模板。

var template = document.getElementById('tmpl').innerHTML; // cache the HTML
function createPageSettingsPopup(page) {
    // Find an replace the {{pageTitle}} with page.title, and then return the HTML string.
    return template.replace(new RegExp('{{pageTitle}}', 'gi'), page.title) 
}

var template = document.getElementById('tmpl').innerHTML; // cache the HTML
function createPageSettingsPopup(page) {
    // Find an replace the {{pageTitle}} with page.title, and then return the HTML string.
    return template.replace(new RegExp('{{pageTitle}}', 'gi'), page.title) 
}

console.log(
   createPageSettingsPopup({title:'Hello World'})
);
<script type="text/template" id="tmpl">
    <div class="form-group">
        <label for="page-title">Title</label>
        <input type="text" class="form-control" id="page-title" value="{{pageTitle}}">
    </div>
</script>

以上是模板引擎的最小示例,但有很多很好的例子,例如mustachehandlebars.jspug.js

答案 1 :(得分:0)

假设ES6你可以使用反引号:

return `<div>
    ...
</div>`;

或者看看react,操纵你的DOM,他们使用jsx非常好:

const element = <h1>Hello, world!</h1>;

如果您使用的是jQuery,有时您可以执行以下操作:

var div = $('div').addClass('form-group');
div.append($('label').attr('for', 'page-title').text('Title');
...

根据您手头的问题,预先编写完整的html结构,然后使用js操作一些内容和样式也是有意义的。在您的示例中:

$('div#title').show();
$('div#title').find('label.page-title').text('Title');

答案 2 :(得分:0)

这看起来不太好,但是另一种在JavaScript中创建元素的方法

使用document.createElement,您可以对要设置的属性进行更多编程控制

function createPageSettingsPopup(page) {
  var div = document.createElement("div");
  div.className="form-group";
  var label = document.createElement("label");
  label.htmlFor="page-title";
  label.textContent="Title";
  var input = document.createElement("input");
  input.type="text";
  input.className="form-control";
  input.id="page-title";
  input.value=page.title;
  label.appendChild(input);
  div.appendChild(label);
  return div;
}

jQuery中相同:

function createPageSettingsPopup(page) {
  var $div = $("<div />",{"class":"form-group"});
  $div.append(
    $("<label />", {"htmlFor":"page-title").text("Title").append(
      $("<input/>", { "type":"text","class":"form-control","id":"page-title"}).val(page.title)
    )
  );
  return $div;
}

答案 3 :(得分:0)

您可以尝试创建一个HTML实用程序,用于创建元素,添加必要的属性和返回元素。

我在示例中创建了一个小实现。这样做的好处是您可以修改此实用程序以使用基于JSON的结构来创建动态HTML。

示例

function createPageSettingsPopup(page) {
  var divParams = {
    class: 'form-group'
  }
  var labelParams = {
    for: 'page-title'
  }
  var inputParams = {
    type: 'text',
    class: "form-control",
    id: 'page-title',
    value: page.title
  }

  var div = utils.createMyElement('div', '', divParams);
  var label = utils.createMyElement('label', 'Title', labelParams)
  var input = utils.createMyElement('input', '', inputParams)

  div.appendChild(label);
  div.appendChild(input);

  document.body.appendChild(div)
}

window.addEventListener('load', function() {
  createPageSettingsPopup({
    title: "foo"
  })
})

// This code can be exported to another file
var utils = (function() {
  function createMyElement(type, htmlString, params) {
    var el = document.createElement(type);
    if (htmlString)
      el.innerHTML = htmlString;
    addProps(el, params)
    return el;
  }

  function addProps(el, props, key) {
    if (Object.keys(props).length) {
      for (var k in props) {
        if (typeof(props[k]) === "object") {
          addProps(el, props[k], k);
        } else {
          if (key) {
            el[key][k] = props[k]
          } else {
            el[k] = props[k]
          }
        }
      }
    }
  }

  return {
    createMyElement: createMyElement
  }
})()

您也可以尝试基于JSON的表单。

<强>示例

JSFiddle

window.addEventListener('load', function() {
  createPageSettingsPopup({
    title: "foo"
  })
})

function createPageSettingsPopup(page) {
  var form = utils.createForm(getFormData(page))
  document.body.appendChild(form)
}

// This can be stored in JSON file or in db and then can be fetched
function getFormData(page) {
  var json = {
    type: "div",
    params: {
      class: 'form-group',
      innerHTML: "",
    },
    children: [{
      type: 'label',
      params: {
        for: 'page-title',
        innerHTML: "Title"
      },
    }, {
      type: 'input',
      params: {
        type: 'text',
        class: "form-control",
        id: 'page-title',
        value: page.title
      }
    }]
  }
  return json
}

// This is a generic utility and can be exported to a utility file
var utils = (function() {
  function JSONBasedForm(form_json) {
    var el = "";
    if (form_json) {
      el = createMyElement(form_json.type, form_json.params);
      if (form_json.children && form_json.children.length > 0) {
        form_json.children.forEach(function(child) {
          var c_el = JSONBasedForm(child)
          c_el && el.appendChild(c_el)
        })
      }
    }
    return el;
  }

  function createMyElement(type, params) {
    var el = document.createElement(type);
    addProps(el, params)
    return el;
  }

  function addProps(el, props, key) {
    if (Object.keys(props).length) {
      for (var k in props) {
        if (typeof(props[k]) === "object") {
          addProps(el, props[k], k);
        } else {
          if (key) {
            el[key][k] = props[k]
          } else {
            el[k] = props[k]
          }
        }
      }
    }
  }

  return {
    createForm: JSONBasedForm
  }
})()