Javascript Jquery$(element).contents().first().text(“新文本”)不';不行?

Javascript Jquery$(element).contents().first().text(“新文本”)不';不行?,javascript,jquery,Javascript,Jquery,我在谷歌或这里找不到任何关于这个的信息 我有一个div,其中包含一些文本和一些html: <div id="test-div"> http://<strong>somewebsite.com</strong>/big/long/unfriendly/path/ </div> 然而,它什么也不做。我知道我的导航是正确的,因为类似这样的东西: $('#test-div').contents().first().wrap( "<b>

我在谷歌或这里找不到任何关于这个的信息

我有一个div,其中包含一些文本和一些html:

<div id="test-div">
    http://<strong>somewebsite.com</strong>/big/long/unfriendly/path/
</div>
然而,它什么也不做。我知道我的导航是正确的,因为类似这样的东西:

$('#test-div').contents().first().wrap( "<b></b>" );
$('#test-div').contents().filter(function(){
    return $.trim($(this).text()) == 'http://';
}).remove().end().prepend('something');
$('#test div').contents().first().wrap(“”);
确实有效

为什么我不能更改文本位? (对于最初的问题,一个更优雅的解决方案也很好)

你试过了吗

$(element).html('your content here');
这样使用:

$('#test-div').contents().first().wrap( "<b></b>" );
$('#test-div').contents().filter(function(){
    return $.trim($(this).text()) == 'http://';
}).remove().end().prepend('something');

或者


用正则表达式替换
/
,怎么样


$('#test div').html($('#test div').html().replace(/(您尝试过类似的方法吗

$('#test-div').html().replace('/', '/<wbr>');
$('#test div').html().replace('/','/');

因为当你说第一次时,它会给你
[对象文本]
而文本属性不能使用它,最简单的解决方案是:

$("#test-div").contents()[0].textContent="Something";

多亏了和项,我终于找到了自己的答案。我现在有了一个函数,可以替换上下文中所有文本节点中的所有文本。它还可以将HTML插入到所述节点中

JavaScript函数:

function recursiveReplace(node, oldValue, newValue) {
    if (node.nodeType === 3) { // text node
        $(node).replaceWith(node.nodeValue.replace(oldValue, newValue));
    } else if (node.nodeType === 1) { // element
        $(node).contents().each(function() {
            recursiveReplace(this, oldValue, newValue);
        });
    }
}

//To call
div = $('#test-div');
recursiveReplace(div[0], "/", "/<wbr />");
函数递归替换(节点、旧值、新值){
如果(node.nodeType==3){//text节点
$(node.replaceWith(node.nodeValue.replace(oldValue,newValue));
}如果(node.nodeType==1){//element
$(节点).contents().each(函数()){
递归替换(this、oldValue、newValue);
});
}
}
//召唤
div=$(“#测试div”);
递归替换(div[0],“/”,“/”;

这以一种通用的方式解决了这个问题。

.text
可能只在元素节点上起作用。这很好:
$('#test div').contents().first()[0]。nodeValue=“something”
我有,但是我最初的问题是需要替换文本位中的斜杠,同时保留所有html标记不变。
function recursiveReplace(node, oldValue, newValue) {
    if (node.nodeType === 3) { // text node
        $(node).replaceWith(node.nodeValue.replace(oldValue, newValue));
    } else if (node.nodeType === 1) { // element
        $(node).contents().each(function() {
            recursiveReplace(this, oldValue, newValue);
        });
    }
}

//To call
div = $('#test-div');
recursiveReplace(div[0], "/", "/<wbr />");