我有一個HTML字符串,它看起來像:用data-hint
屬性輸入如何包圍容器中的元素?
var form = '<form data-hint="blah">' +
'<label for=\"password0\">Password0</label>' +
'<input type=\"password\" name=\"password0\" id=\"password0\" data-hint=\"Please enter your Password 0\" />' +
'<label for=\"password1\">Password 1</label>' +
'<input type=\"password\" name=\"password1\" id=\"password1\" data-hint=\"Please enter your Password 2\" />' +
'</form>';
我想SEACH字符串(使用jQuery,但開放的替代品)。然後,我想將找到的輸入及其伴隨的標籤包圍在一個div容器中。因此,例如,當打印出上面的字符串應該像樂:
<form data-hint="blah">
<div>
<label for=\"password0\">Password0</label>
<input type=\"password\" name=\"password0\" id=\"password0\" data-hint=\"Please enter your Password 0\" />
</div>
<div>
<label for=\"password1\">Password 1</label> +
<input type=\"password\" name=\"password1\" id=\"password1\" data-hint=\"Please enter your Password 2\" />
</div>
</form>
這裏是我的代碼:
$(form).find('input[data-hint]').each(function() {
id = $(this).attr('id');
//put <div> before the label
form = $(self.form).find('label[for=' + id + ']').before('<div>').parents('form')[0].outerHTML;
//put the closing div after the input
form = $(self.form).find('input#' + id).after('</div>').parents('form')[0].outerHTML;
});
但我結束了與jQuery的label
之前和之後input
插入<div></div>
...
的的jsfiddle是here
只需將「self.form」替換爲「form」即可。這將消除錯誤 – jevgenig 2014-10-01 14:21:19
編輯問題 – Mark 2014-10-01 14:26:20
你有沒有嘗試過使用jQuery .wrap()和.wrapInner()? – trnelson 2014-10-01 14:26:37