javascript 附加 div 并将其宽度设置为与锚文本相同

javascript append div and set its width same as an anchor text

我正在尝试以编程方式创建 div,将其附加到 parent div,并将这个新创建的 div 的宽度设置为等于<a>...</a>、child 和 parent div(它的兄弟)中的文本宽度。

html:

<div id='div0'>
 <a href="#">text</a>
</div>

js/jquery:

        var curDiv = document.getElementById('div0');
        var iDiv = document.createElement('div');
        iDiv.id = 'newDivId';
        iDiv.className = 'newDivClass';
        curDiv.appendChild(iDiv);

        // the div is appended successfuly
        // next step below doesn't work

        var curTxt = $('#div0').next("a").text();
        var curWidth = curTxt.width();

        $('.newDivClass').css('width', curWidth);

我使用 .log 得到的是那个变量 curTxt = (empty),它也 returns 这个错误:curTxt.width is not a function.

不需要 JS。只需将 div 设置为 display : inline-block.

#div0 {
   border: green solid 3px;
   display : inline-block;
}

a {
   border : blue solid 3px;
   font-size : 2rem;
}
<div id='div0'>
 <a href="#">text</a>
</div>

你可以做到这一点

var curDiv = document.getElementById('div0');
var iDiv = document.createElement('div');
iDiv.id = 'newDivId';
iDiv.className = 'newDivClass';
iDiv.style.background = "red"
iDiv.style.height = "10px"
curDiv.appendChild(iDiv);

// the div is appended successfuly
// next step below doesn't work

var curWidth = $('#div0 > a').width();

console.log(curWidth)


$('.newDivClass').css('width', curWidth);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='div0'>
 <a href="#">text</a>
</div>

你的主要问题是 next() 似乎在寻找兄弟姐妹,而 link 是 child