1

Here's what I have. A SharePoint 2010 custom view in a list web part. I have 6 categories and 4 sub-categories. Items do not have to have sub-category but do have to have a category.

The view shows the a blank sub-category witha number next to it. I'm trying to bind a click event to all of them but the ID increases on every page refresh. The base ID is titl[0-9]*[0-9]. Then there is another ID underneath that I want to check as well, it is titl[0-9]*_[0-9]1.

So I've tried using the regex selector for jQuery and it doesn't bind correctly. It finds the object but doesn't bind correctly.

I need it to bind to the id and then be able to trigger the onclick event of the next tbody which is the 1_. Then check if the text of it is " " and if so hide the tbody.

My code:

$(":regex(id,titl[0-9]*-[0-9]_) td a").bind('click', function(){
  var parent = $(this);
  var child = $(this).next("tbody");
  var grandchild = $(this).next("tbody td a");
  //alert(parent + " | " + child + " | " + grandchild ); //always return undefined??
  // Everything below works if I can get the IDs correct for child and grandchild
  if($(grandchild).css('display')!='none'){
    $(grandchild).click();

    if($(grandchild).text()==" "){
      $(child).hide();
    };
  };
}); 
4

3 回答 3

1

我强烈建议您重新考虑您的 ID - 它们应该是一致的,真的。

如果您绝对必须使用变量 ID,您可以在选择器中使用“id”属性,就像使用任何其他属性一样:

// Any element, ID starts with "titl"
$('[id^="titl"]')

要捕获并重新使用它,我真的建议您对您的 ID 做错了什么。然而,为了完整性(尽管我不能强调你应该尽量避免使用它),基于此的东西应该是一个好的(哈哈,是的)起点

// Long-winded messy hideous foul code
var $title = $('[id^="titl"]'),
    title = $title.length && $title.eq(0).attr('id');
if (title !== 0)
{
    $('#' + title + ' #' + title + '1 td a').html('Ow.');
}
于 2012-10-15T23:03:11.587 回答
0

如果您可以控制身份,我同意重新考虑您的身份。即使您不这样做,StartsWith 选择器也会为您提供所有更高级别的元素,并且您可以遍历到较低级别的元素。请记住,链接选择器意味着您可以匹配 id 中的相似模式,而无需关注实际

另一个注意事项:我从来不需要使用 jQuery 进行正则表达式匹配。类似 CSS3 的选择器功能太强大了。

于 2012-10-16T02:20:17.793 回答
0

我不确定我是否明白这一点,但您可以定位任何以 开头titl的 ID,然后在函数内以许多其他方式根据 ID 进行过滤:

$('[id^="titl["]').on('click', function() {
    var check = this.id.charAt(10) == '_', //tenth character is underscore ?
        parent = $(this),
        child = $(this).next("tbody"),
        grandchild = $(this).next("tbody td a");

    if (check) {
        //element matching second selectortype clicked
    }else{
        if (grandchild.is(':visible')){
            grandchild.trigger('click');
            if (grandchild.text()==" ") child.hide();
        }
    }
});
于 2012-10-15T23:02:52.227 回答