[英]Add html attribute to string
I am appending some html to a div using jQuery, where both rowString
and inputString
are defined previously: 我正在使用jQuery将一些html附加到div上,其中
rowString
和inputString
都是先前定义的:
$("#filterContainer").append(
rowString +
`<label class='filterLabel' for=${filter}>${filter}</label>` +
"<i class='fas fa-minus-circle removeFilter float-right'></i>" +
inputString +
"</div>"
);
rowString
looks like this: rowString
看起来像这样:
let rowString = "<input id='autocomplete' type='search' class='form-control' name='filters[location]' >"
And I am trying to inject a value into this. 我正在尝试为此注入价值。 I've tried
rowString.val('myvalue')
, but it fails with Uncaught TypeError: string.val is not a function
. 我已经尝试过
rowString.val('myvalue')
,但失败,并出现Uncaught TypeError: string.val is not a function
。
How can I add an html attribute such as value
to a string? 如何在字符串中添加html属性(例如
value
?
$(rowString).attr('value', 'myvalue').prop('outerHTML')
You can parse it, set the value, and then get the outerHTML to get the HTML back. 您可以解析它,设置值,然后获取outerHTML以获取HTML。
let rowString = "<input id='autocomplete' type='search' class='form-control' name='filters[location]' >"; console.log( $(rowString).attr('value', 'myvalue').prop('outerHTML') );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
$(rowString).val('myvalue')
并且,更改您的追加对此:
$("#filterContainer").append(`${rowString}<label class='filterLabel' for=${filter}>${filter}</label><i class='fas fa-minus-circle removeFilter float-right'></i>${inputString}</div>`);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.