【问题标题】:How to set the content of an element to value of its attribute with jQuery如何使用jQuery将元素的内容设置为其属性的值
【发布时间】:2016-03-23 08:18:26
【问题描述】:

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

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

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

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

&lt;div data-test-id="3214581"&gt;John, Smith&lt;/div&gt;

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

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

getPersonName() 返回“约翰,史密斯”

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

编辑:固定元素显示多个 div,而不仅仅是一个。 (即 ID 未知,不应在选择器中)。固定选择在它周围有单引号。

【问题讨论】:

  • 您的期望反映了对how this works的根本误解。
  • 您的选择器似乎不正确。选择器是一个字符串:$('div[data-test-id])`....
  • 你可以使用each函数-$(div[data-test-id]).each(function(){ $(this).text(getPersonName($(this).data('testId'))); });
  • 您能否在问题中包含getPersonName 的文字?

标签: javascript jquery dom-manipulation


【解决方案1】:

this 是函数的上下文。

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

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

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

【讨论】:

  • 这是正确的,只是你忘记了return getPersonName。该函数应返回字符串,并将其放在 text() 中。谢谢!
【解决方案2】:

很遗憾,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')));
});

【讨论】:

  • 或 .text() 接受一个回调函数,该函数将为每个匹配的元素调用,因此不需要 .each()。
  • 这是真的,如果你有一个返回一些东西的函数。 @moonwave99 知道了,但他忘记了 return 关键字。
【解决方案3】:

我很好奇纯javascript翻译与moonwave99的答案相比要多长时间。以防万一有人对此也感兴趣,这里是:

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

jsfiddle

【讨论】:

  • .innerHTML = .text() 调用非常不同。
  • for (let el of document.querySelectorAll("div[data-test-id]")) el.textContent = getPersonName(el.dataset.testId); 应该这样做。
【解决方案4】:

没有必要使用迭代方法; .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>

【讨论】:

    猜你喜欢
    • 2015-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-13
    • 2021-04-12
    • 2011-03-31
    • 1970-01-01
    相关资源
    最近更新 更多