为什么嵌套在功能中时,.setAttribute不起作用?

发布于 2025-01-20 06:42:16 字数 639 浏览 2 评论 0原文

我会快速。我研究了很多,但我不确定为什么这不起作用。

我有一个Textarea标签,我想使用setAttribute(“ data-something”,“”)命令将其设置为“数据浪潮”标签,如果我只是在那里列出它,它可以正常工作。但是,我正在做的是“创建一个按钮,当单击时,将Textarea的属性设置为'Data-something'的属性,无论当我将setAttribute嵌套在myfunction中并设置按钮onclick = onclick =时,它无法操作。 myfunction(

<textarea></textarea>

<script>
textarea.setAttribute("data-something","")
</script>

<textarea></textarea>

<button onclick="myFunction()"></button>

<script>
function myFunction(){
textarea.setAttribute("data-something","")
}
</script>

I'll make it quick. I researched a lot but I'm not sure why this is not working.

I have a textarea tag which I want to set to 'data-something' tag using setAttribute("data-something","") command and it works just fine if I just list it out there. However what I'm doing is I"m creating a button that when clicked sets the attribute of the textarea to 'data-something', and no matter what it fails to operate when I nest setAttribute inside a myFunction and set button onclick="myFunction()". I'd appreciate if someone could explain a workaround that.

Thanks a ton for your patience.

This is what works:

<textarea></textarea>

<script>
textarea.setAttribute("data-something","")
</script>

This is what doesn't work

<textarea></textarea>

<button onclick="myFunction()"></button>

<script>
function myFunction(){
textarea.setAttribute("data-something","")
}
</script>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

橘味果▽酱 2025-01-27 06:42:16

您必须为元素提供一个句柄 getElementById 然后进行更改

function myFunction(){
  let textarea = document.getElementById("Foo");
  textarea.setAttribute("data-something","This is the set Data");
  console.log(textarea);
}
<textarea id="Foo"></textarea>

<button onclick="myFunction()">Click me</button>

You have to give you element a handle getElementById then make the change

function myFunction(){
  let textarea = document.getElementById("Foo");
  textarea.setAttribute("data-something","This is the set Data");
  console.log(textarea);
}
<textarea id="Foo"></textarea>

<button onclick="myFunction()">Click me</button>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文