javascript - 用 JS 重写 HTML

标签 javascript jquery html

在我的 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/

相关文章:

javascript - 解析云代码 Mandrill Promise

javascript - Jquery 无法选择链接内的图像

javascript - 如何使用 JavaScript 将事件监听器添加到服务器返回的不同数量的元素中

javascript - 如何使用jquery获取div内链接的href?

html - 替换 "hover"上的动态背景 - Ruby on Rails

javascript - “仅限数字指令”在 Chrome 49.xx.xx 及更低版本中不起作用

javascript - 将对象的特定键值数组转换为逗号分隔的字符串

html - 在多行跨度中添加三个点

javascript - odoo 10 - "Overwriting"来自旧模块的 Javascript 代码

jquery - 锁定元素相对于另一个元素的位置