【问题标题】:Mystery characters appear when I use insertAdjacentHTML("beforeend" ... to add an element to the DOM当我使用 insertAdjacentHTML("beforeend" ... 向 DOM 添加元素时出现神秘字符
【发布时间】:2021-05-14 17:04:44
【问题描述】:

我对 javascript 和 php 还比较陌生,我一直在研究这个问题几个小时,但没有成功。

我正在从数据库中检索列表项的网页上创建一个列表。创建列表的 php 代码如下所示:

$options = get_option( 'psb_config' );
$n = 0;
echo '<ul id="session-type-list">';
foreach ( $options['type'] as $t ) {
    $html = '<li id="' . $t . '-field"><input id="' . $t . '-psb" type="text" class="type-btn" size="20%" value="' . $t . '" name="psb_config[type][' . $n . ']">';
    $html .= '<input type="button" class="button" value="remove" onclick="removeTypeButton(&#34' . $t . '-field&#34)"></li>';
    echo $html;
    $n++;
}
echo '</ul>';

此列表中的每个条目都有文本输入字段和一个带有 onClick 函数调用 onclick="removeTypeButton(&amp;#34' . $t . '-field&amp;#34)"&gt; 的删除按钮。 removeTypeButton() 函数是一个简单的 javascript:

function removeTypeButton( id ) {
    document.getElementById( id ).remove();
}

而且效果很好。

我还希望用户能够向列表中添加字段,并且我在列表末尾有一个添加会话按钮,它调用以下 javascript 函数:

function addTypeButton( n ) {
    var node = document.getElementById("session-type-list");
    var id = '\"field-' + n + '\"';
    var html = '<li id=' + id + '>';
    html += '<input id="psb-' + n + '" type="text" class="type-btn" size="20%" placeholder="new shoot type" name="psb_config[type][' + n + ']">';
    html += '<input id="btn-' + n + '" type="button" class="button" value="remove" onClick="removeTypeButton(' + id  + ')"></li>';
    node.insertAdjacentHTML("beforeend", html);
}

此函数通常按预期工作,但有一个例外:在它插入文本字段和&lt;ul&gt; 列表末尾的删除按钮后,删除按钮的 HTML 变得混乱。

我的 HTML 字符串是:

<input id="btn-' + n + '" type="button" class="button" value="remove" onClick="removeTypeButton(' + id  + ')"></li>

当我在浏览器中检查元素时,字符串看起来像这样:

<input id="btn-10" type="button" class="button" value="remove" onclick="removeTypeButton(" field-10")"="">

removeTypeButton(" field-10")"=""&gt; 参数搞砸了!还有额外的引号和等号。

我一直在尝试转义引号和其他恶作剧,包括 jQuery,但没有成功。似乎该字符串被解释为好像 onClick 函数在 ( 之后结束并且参数被解释为另一个标签。

所以我的问题是:我做错了什么?我已经在谷歌上搜索了几个小时,stackoverflow 是我最后的选择。

非常感谢任何提示。

【问题讨论】:

  • 如果你在 JS 中切换它会发生什么,你在 add 函数中设置 id var id = '\"field-' + n + '\"'; 将其更改为 var id = "\'field-" + n + "\'";
  • 谢谢!这就是我之前尝试过的,但没有奏效。下面来自@rjdown 的解决方案有效。

标签: javascript php html dom


【解决方案1】:

如果您查看页面源代码,而不是检查元素,您会发现它以这样的方式结束

onClick="removeTypeButton("field-10")"&gt;

双引号内的双引号可能会混淆浏览器。将内引号转换为单引号。

var id = '\'field-' + n + '\'';

这应该有预期的效果:

onClick="removeTypeButton('field-10')"&gt;

【讨论】:

    猜你喜欢
    • 2018-01-18
    • 2012-05-31
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多