【问题标题】:Add a value to an id only if it is empty仅当 id 为空时才向其添加值
【发布时间】:2018-01-04 19:43:27
【问题描述】:

如果当前 id 为空,我想添加一个 id。我认为这可以完成这项工作:

$(".file-row[id='']").attr('id', 'imageId'+imageId);

但事实并非如此。为什么不呢?

【问题讨论】:

  • 那里有id属性吗?
  • 使用 prop 代替 attr。我警告你。它不会像你认为我会做的那样工作
  • 是的,.file-row get 是由 dropzoneJS 添加的,并且还添加了一个 id 属性。
  • 另外你需要这样使用选择器:$(".file-row:not([id])")
  • 希望这个逻辑只会捕获一个元素原因,你知道,重复的 ids === 不好

标签: jquery html dropzone


【解决方案1】:

如果 id 为空或全部缺失,则设置 id。

$('div').filter('[id=""],:not([id])').prop('id', 'newId');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="">One</div>
<div>Two</div>
<div id="three">Three</div>

【讨论】:

    猜你喜欢
    • 2011-08-12
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    • 2018-07-18
    • 2015-07-29
    • 2013-03-09
    相关资源
    最近更新 更多