如何使用 jQuery 将元素的内容设置为其属性的值

How to set the content of an element to value of its attribute with jQuery

这只是我在玩jsFiddle时想到的一个练习。

给定具有数据属性的元素:

<div data-test-id="3214581">Loading...</div> <div data-test-id="6584634">Loading...</div>

我想将文本内容设置为具有该 ID 的函数的结果,这样最终的 DOM 是:

<div data-test-id="3214581">John, Smith</div>

到目前为止,我能够找到给定的元素,但不知何故无法使用 this 关键字引用该元素以获取其 testId:

$('div[data-test-id]').text(getPersonName($(this).data('testId')))

getPersonName() returns "John, Smith"

我认为应该这么简单,但在堆栈或 jQuery 文档中没有找到像这样的自引用示例。

编辑:固定元素以显示多个 div,而不仅仅是一个。 (即 ID 未知,不应在 selector 中)。修复了 select 周围有单引号。

this是函数的上下文。

如果没有进一步说明,this 就是 window

您想要的是将回调传递给 $.text,它将绑定到选定的 DOM 元素:

$('div[data-test-id]').text(function(){
  // here this is your div
  return getPersonName($(this).data('testId'))
})

不幸的是,this 关键字无法帮助您在当前上下文中执行此操作。您需要使用 jQuery 的 each 来遍历 $(div[data-test-id]) 查询的结果。然后,在给每个人的回调中,this 的值将绑定到 DOM 节点。

// "this" in this scope is not the DOM element
$(div[data-test-id]).each(function() {
  // "this" inside this scope is bound to the DOM element
  $(this).text(getPersonName($(this).data('testId')));
});

我很好奇纯 javascript 翻译比 moonwave99 的回答要长多少。万一有人对此也感兴趣,这里是:

[].forEach.call(document.querySelectorAll("div[data-test-id]"),function(el){
    el.innerHTML=getPersonName(el.getAttribute("data-test-id"));
});

jsfiddle

没有必要使用迭代方法; .text() 迭代选择器中的每个元素,this 已经是 .text(function(index, text){}).

函数中的当前元素

您可以将 getPersonName 调整为 .text() 的签名,这样您就可以使用模式

$("div[data-test-id]").text(getPersonName);

var names = {
  3214581: "John, Smith",
  6584634: "Stack, Overflow"
}

function getPersonName(index, text) {      
  return names[$(this).data().testId]
}

$("div[data-test-id]").text(getPersonName);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div data-test-id="3214581">Loading...</div>
<div data-test-id="6584634">Loading...</div>