【问题标题】:jQuery retrieve closest-to-unique selectorjQuery 检索最接近唯一的选择器
【发布时间】:2012-07-16 23:41:10
【问题描述】:

所以你有一堆元素,你用 jQuery 选择其中一个。

($('div > ul > li').length === 1) // this is true

现在,如果您需要将此元素作为字符串传递,您通常会:

var el = $('div > ul > lu');
var passid = el.prop('id');

// in case this element doesn't have an id="..." attribute set one
if(typeof(passid)!=='string'){
    // compute an id="..." attribute based on the time
    var elindex = new Date().getTime();
    // make sure the id we're using isn't already in use by a different element
    while($('#el_'+elindex).length)
        elindex++;

    // assign what we've got
    passid = 'el_'+ elindex ;
    el.prop('id', passid);
};
passid = '#'+passid;

// Once we're good to go, pass the resulting selector
// passon(passid);... etc.

jQuery 是否带有更好的(内置)函数(甚至是插件)来方便我将 DOM 节点的引用作为字符串传递?

【问题讨论】:

  • 我不知道我是否会“疯狂地”这样做。
  • 为什么要将 DOM 元素的引用作为字符串传递?只需传递对元素本身的引用即可。
  • @nnnnnn 这是一个状态更新指示元素,我将它发送到 WebSocketServer。实在不能作为参考。

标签: javascript jquery css-selectors


【解决方案1】:

假设您一次只进行一次状态更新,为什么不能简单地给元素一个临时 id,如“current_el”,然后当 websocket 返回时,您可以简单地访问带有 id 的元素“current_el”每次?所以基本上,你设置一个每次都相同的临时 id。这样你甚至根本不需要发送选择器,你可以简单地访问临时 id 并在服务器请求返回时将其清除。

但是,如果您需要保留参考以供将来使用该元素,您的方法似乎还不错。我不知道任何旨在实现此目的的 jQuery 函数。希望这可以帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    • 2021-05-11
    • 1970-01-01
    • 2018-04-02
    • 2014-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多