【问题标题】:Call each item when multiple selector perform in jQuery在jQuery中执行多个选择器时调用每个项目
【发布时间】:2016-06-17 17:51:46
【问题描述】:

我想将每个复选框的.parent("span").prop("title") 设置为其.parent("span").parent("td").parent("tr") 的标题。由于 jQuery 在有多个元素时会迭代执行,所以我不能在没有循环的情况下做这样的事情吗?

$(":checkbox").parent("span").parent("td").parent("tr").prop("title", $(this).parent("span").prop("title"));

在浏览器中呈现类似这样的内容。

<tr class="GridRow_Default" id="ctl00_body_grdTime_ctl00__2">
    <td align="center">
        <span title="Regularizable">
            <input id="ctl00_body_grdTime_ctl00_ctl07_chkSub" type="checkbox" name="ctl00$body$grdTime$ctl00$ctl07$chkSub">
        </span>
    </td>       
</tr>

【问题讨论】:

    标签: javascript jquery loops multipleselection


    【解决方案1】:

    我不能在没有循环的情况下做这样的事情吗?

    否。要获取当前元素引用,您必须遍历元素。

    您可以使用each() 遍历所有复选框。

    $(':checkbox').each(function () {
        // `$(this)` here is the current checkbox
    
        $(this)
            .closest('tr') // Get closest ancestor `<tr>`
            .attr('title', $(this).parent().attr('title')); // Set attribute value of `title` to that of the `parent`
    });
    

    【讨论】:

    • 我认为 OP 希望在不使用循环的情况下实现这一目标。 can n't I do something like this without a loop?
    • @RinoRaj 是的,但那是不可能的。我已经添加了描述。
    • @RayonDabre 来自 jQuery 源,propattr 设置器使用 access()。以下是 jQuery.fn.extend( { prop: function( name, value ) { return access( this, jQuery.prop, name, value, arguments.length &gt; 1 ); },access 迭代元素的方式,var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { ...... if ( fn ) { for ( ; i &lt; length; i++ ) { fn( elems[ i ], key, raw ? value : value.call( elems[ i ], i, fn( elems[ i ], key ) ) ); } }
    • @Tushar,是的,你是right
    • @Nishantha 是的,但那是使用两个循环。一种是获取&lt;tr&gt;s,其中包含复选框,然后获取title 属性。
    【解决方案2】:

    使用 filter() 只获取包含 INPUT:CHECKBOX 元素的 SPAN 的 TR,并将 SPAN 的 title 属性的值设置为 TR。

    $('tr').filter(function() {
        return $(this).find('span > :checkbox').length; 
    }).prop('title', function() { return $(this).find('span').eq(0).prop('title'); });
    

    【讨论】:

      【解决方案3】:

      尝试使用:has().prop(function(propertyName, function).closest()

      $("span:has(:checkbox)").prop("title", function(index, prop) {
        return $(this).closest("tr").prop("title");
      })
      

      【讨论】:

        猜你喜欢
        • 2011-10-17
        • 2010-10-20
        • 2010-12-19
        • 1970-01-01
        • 1970-01-01
        • 2011-01-09
        • 1970-01-01
        • 2016-11-25
        • 1970-01-01
        相关资源
        最近更新 更多