无法将正确的 ID 传递给 .replaceWith()

Can't pass right ID to .replaceWith()

我知道答案可能会很简单,但我因为没有让它起作用而失去了理智:

<button id="buttonid<?php echo $i?>" onclick="addShift(this.id)">+</button>
<script>
    function addShift(id){
        alert(id);
        $('#id').replaceWith( "<h2>TEST</h2>" );        
    }
</script>

警报显示正确的 ID。但我无法使 .replaceWith 函数正常工作。

$("button").replaceWith( "<h2>TEST</h2>" );

顺便说一句,这是有效的。关于将 html ID 提交给 javascript,我在这里遗漏了什么?谢谢!

我可能误解了问题,但我认为这是因为您使用的是字符串 '#id' 而不是 id.

的值

试试这个:

<button id="buttonid<?php echo $i?>" onclick="addShift(this.id)">+</button>
<script>
    function addShift(id){
        alert(id);
        $('#'+id).replaceWith( "<h2>TEST</h2>" );        
    }
</script>

您可能认为 Javascript 在支持字符串插值方面与 PHP 类似。这意味着,让您在 PHP 中执行类似 $variable = 'me'; echo "$variable is cool"; 的操作,并打印出 me is cool。但是 Javascript 不会那样做。您需要改用字符串连接,即 alert(variable + ' is cool').