javascript - Replace name attr with current name + another string with jQuery?
问题描述
I have this code:
var prodElem = $('#dropTitle').text();
$(prodElem).clone(true, true).appendTo('#orders')
.attr("name", $(this).attr("name") + "-1");
but the name attribute is being replaced by -1.
How can I utilize "this" in order to achieve the current name and append -1 to the end?
Thanks!
解决方案
this
in that code doesn't refer to the element(s) you're setting the name on. My guess is this code is running where this
refers to window
, and so $(this).attr("name")
returns the window name (which is usually blank), so you're setting name
on all of those elements to "" + "-1"
, which is of course, "-1"
.
You can use the version of attr
that accepts a callback:
$(prodElem).clone(true, true).appendTo('#orders')
.attr("name", function() {
return $(this).attr("name") + "-1";
});
There, this
refers to each matching element.
Side note: If this is really the name
attribute, it's reflected by the property name
, so you could also do it with prop
and get the reflected attribute directly in the function:
$(prodElem).clone(true, true).appendTo('#orders')
.prop("name", function() {
return this.name + "-1";
});
推荐阅读
- node.js - 无法在 nodejs 上使用用 emscripten 编译的 js 库,但如果我启动交互式 nodejs shell,它就可以工作
- java - 登录在 Spring Security 的自定义登录页面中不起作用
- java - Mp3 文件不会在 Linux 上使用 jlayer 转换为 .wav,但会在 macOS 上
- php - 设置选择输入值 unsing php echo
- hadoop - Apache Zeppelin 失败 java.lang.NoClassDefFoundError: org/apache/hadoop/conf/Configuration
- jsf - commandButton actionListener 在 Primefaces 10.0 中不起作用
- docker - 为什么我的 nextflow 脚本中的奇点拉取失败?
- uwp - 如何为 InkToolbarBallpointPenButton 自定义自定义调色板的悬停行为?
- php - Plupupload - 上传前提交表单
- python - Flask AppBuilder如何在模型插入或更新后插入或更新其他表