javascript 在jquery中选择ID+任意数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18129870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:49:11  来源:igfitidea点击:

Selecting ID + any number in jquery

javascriptjquerystringjquery-selectors

提问by Fernanda Nia Ferreira

I'm new to stackoverflow and jQuery altogether, so I'm having a little trouble making a simple function.

我完全是 stackoverflow 和 jQuery 的新手,所以我在制作一个简单的函数时遇到了一些麻烦。

I basically have in my website a random number of links with id "filtro" + "some number", and I want to write only one code to the action of clicking in any of them (that would later impact on the class with same "filtro" + "some number").

我基本上在我的网站上有一个随机数量的链接id "filtro" + "some number",我只想编写一个代码来点击其中任何一个的操作(这将在以后影响具有相同“过滤器”+“一些数字”的类)。

Eg.: Click "#filtro3", do something on ".filtro3".

例如:点击“#filtro3”,对“.filtro3”做一些事情。

The problem is, I don't know how to write the string in jQuery for "any number". I'm thinking about doing something like this:

问题是,我不知道如何在 jQuery 中为“任意数字”编写字符串。我正在考虑做这样的事情:

$(function () {
    $("#" + "filtro" + SOME NUMBER).click(function () {
            //Do something with the element "." + "filtro" + SOME NUMBER
    });
});

Any ideas? Thank you!!

有任何想法吗?谢谢!!

Ps.: This is my first question, and I apologize if I made any mistakes.

Ps.:这是我的第一个问题,如果我犯了任何错误,我深表歉意。



SOLVED. dystroy's solution worked like a charm.

解决了。dystroy 的解决方案就像一个魅力。

For future reference to others, I was making this code to make a simple filter menu for a picture gallery. This way I could hide/show pictures of certain topics.

为了将来供他人参考,我正在编写此代码来为图片库制作一个简单的过滤器菜单。这样我就可以隐藏/显示某些主题的图片。

回答by Denys Séguret

You seem to want

你似乎想要

$(function () {
    $("[id^=filtro]").click(function () {
        var num = this.id.slice(6);
        // if there is a risk of ambiguity, you might check here that +num==num
        var $elem = $('.filtro'+num);
        ...
    });
});

Explanations :

说明:

  • $("[id^=filtro]")uses the starts with selectorto select all elements whose id starts with "filtro"
  • this.id.slice(6);takes the part of the id starting after the sixth character. Maybe it would be clearer as this.id.slice('filtro'.length)or this.id.substring('filtro'.length)
  • $("[id^=filtro]")使用以选择器开始选择id 以“filtro”开头的所有元素
  • this.id.slice(6);从第六个字符开始的 id 部分。也许它会更清楚this.id.slice('filtro'.length)this.id.substring('filtro'.length)

回答by James Lim

There are some good answers to your original question, but I would like to suggest a potentially cleaner alternative.

您最初的问题有一些很好的答案,但我想建议一个可能更清洁的替代方案。

You could use data-*attributes instead of IDs for selecting your elements. For example, your elements could look like

您可以使用data-*属性而不是 ID 来选择元素。例如,您的元素可能看起来像

<a data-filtro=6 href='...'>link</a>
<a data-filtro=7 href='...'>link</a>
<a data-filtro=8 href='...'>link</a>

Then you can select these elements using $('[data-filtro]')and use $(this).data('filtro')inside the callback. For example,

然后您可以在回调中使用$('[data-filtro]')和使用来选择这些元素$(this).data('filtro')。例如,

$("[data-filtro]").click(function() {
  var ele = $(this);
  var num = ele.data('filtro');
  // do whatever you want with num
});

This technique is used in many places, including the Foundation framework. It makes it easier to extract your behavior into a separate plugin that isn't dependent on element IDs. As the application becomes more complicated and the number of behaviors tied to each element grows, each element will look like

这种技术在很多地方都有使用,包括 Foundation 框架。它可以更轻松地将您的行为提取到不依赖于元素 ID 的单独插件中。随着应用程序变得越来越复杂并且与每个元素相关的行为数量增加,每个元素看起来像

<a data-filtro=6 data-foo data-bar href="...">link</a>

instead of

代替

<a id="filtro-6_and_bar_and_foo" href="...">link</a>

回答by talemyn

If the idof the clicked element and the classof the elements that you want to change are the same, then it should be as simple as using the idof the element as the input for the class selector:

如果被id点击的元素的 和class你想改变的元素的 是一样的,那么应该像使用id元素的 来作为类选择器的输入一样简单:

Using your code as a base:

使用您的代码作为基础:

$(function () {
    $("[id^=filtro]").click(function () {
        $("." + $(this).prop("id")).some_method_here();
    });
});

For example, I'm assuming that the target elements are <div>s . . . this would cause any <div>elements with the matching class to display in red text:

例如,我假设目标元素是<div>s 。. . 这将导致<div>具有匹配类的任何元素以红色文本显示:

$(function () {
    $("[id^=filtro]").click(function () {
        $("div",  "#filterTest").css("color", "#000000");
        $("." + $(this).prop("id")).css("color", "#FF0000");
    });
});

Since I see you're new to JQuery . . .

因为我看到你是 JQuery 的新手。. .

  • As dystroy said, $("[id^=filtro]")selects all elements that have and idthat begin with "filtro".
  • $(this).prop("id")gets the idof the current element (i.e., the one that has just been clicked)
  • $("." + $(this).prop("id"))takes that idand makes it part of a class selector, by adding the "." to the beginning. This will select all elements that have a classvalue that is the same as the idvalue of the element that you clicked.
  • 正如dystroy所说,$("[id^=filtro]")选择所有id具有“filtro”并以“filtro”开头的元素。
  • $(this).prop("id")获取id当前元素的(即刚刚被点击的那个)
  • $("." + $(this).prop("id"))id通过添加“.”来获取它并使其成为类选择器的一部分。到开始。这将选择值与您单击的元素classid值相同的所有元素。

Edit:- you could also use this.id(standard JavaScript) in place of $(this).prop("id"), which is simply JQuery's way of accomplishing the same thing.

编辑:- 您也可以使用this.id(标准 JavaScript)代替$(this).prop("id"),这只是 JQuery 完成相同事情的方式。

回答by Roko C. Buljan

$("[id^=filtro]").click(function() {
     $('.someClassName'+ this.id.match(/\d+/) ).toggle();      
});

LIVE DEMO

现场演示

The ^in [id^=filtro]is the "Starts With"selector which will matchany element
which ID starts withfiltro

^[id^=filtro]该是“打头的”选择器,将match任何元件
,其ID与开始filtro

Now let's use a bit of Regex to retrieve the number out of the ID,
this.id.match(/\d+/);gets the "this clicked element ID" name and retrieves all numbers d+
That number is than used to match your CLASS element selector.

现在让我们使用一些正则表达式从 ID 中检索数字,
this.id.match(/\d+/);获取“此点击元素 ID”名称并检索所有数字d+
该数字用于匹配您的 CLASS 元素选择器。