在我的 Javascript 应用程序中,我从端点接收到一行 HTML 代码。我无法更改从该端点收到的 HTML 内容。我想将单选按钮转换为常规按钮,但不确定如何重写它。我收到的 HTML 可以包含任何内容 - 我只想替换单选按钮。
这是我可能会得到的字符串:
<form>
<input type="radio" name="a" value="1">Option 1
<br>
<input type="radio" name="a" value="2">Option 2
</form>
我想把它转换成这个字符串:
<form>
<input type="button" id="button-a-1" value="Option 1">
<br>
<input type="button" id="button-a-2" value="Option 2">
</form>
这是目前的使用方式:
$.post('url', data, function(resp) { $('#content').html(resp.html); });
我想我可以通过将 type="radio"查找/替换为 type="button"来完成此操作,但我不确定如何通过操作字符串将输入标签后的文本放入值标签中。并在其中获取一个 ID,以便我可以将事件处理程序绑定(bind)到它。
最佳答案
使用 DOM 而不是使用字符串更容易做到这一点。将其创建为碎片,选择元素并替换它们。
const responseText = `
<form>
<input type="radio" name="a" value="1">Option 1
<br>
<input type="radio" name="a" value="2">Option 2
</form>
`
// create temp element and set the html to it
var temp = document.createElement('div')
temp.innerHTML = responseText
// find the radio buttons
var radios = temp.querySelectorAll('input[type="radio"]')
// loop over each one so we can convert it
radios.forEach(function (rb) {
// create a button
const button = document.createElement('input')
button.type = 'button'
// set the id with the radio button attributes
button.id = `button-${rb.name}-${rb.value}` // = `button-' + rb.name + '-' + rb.value'
// read the next sibling's text and set the value to
button.value = rb.nextSibling.nodeValue.trim()
// remove the text node
rb.nextSibling.remove()
// replace the radio button with your new button
rb.replaceWith(button)
});
console.log(temp.innerHTML)
关于javascript - 用 JS 重写 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57612652/