如何使用jQuery获取属性值并从结果中提取子字符串

时间:2016-08-23 18:57:44

标签: jquery arrays

我有一个文本输入列表,我希望根据某些选择输入的值来操作它们的值。这两组输入具有带并行结构的ID,例如:

<select id="foo-dog-bar>, <input type="text" id="foo-dog-baz>
<select id="foo-cat-bar>, <input type="text" id="foo-cat-baz>
<select id="foo-fish-bar>, <input type="text" id="foo-fish-baz>
<select id="foo-bird-bar>, <input type="text" id="foo-bird-baz>

为了能够找到匹配的文本输入,我需要搜索具有相应ID的选择输入。在上面的示例中,这是在其中间具有相同动物名称的ID。

这是我到目前为止的问题,我的问题是如何处理criteria变量:

jQuery('select[id$="-points"]').change(function() {

    var value = jQuery(this).val(),
        arr = ['cat', 'dog', 'fish', 'bird'],
        criteria = jQuery(this)..., // whichever string in arr its ID contains
        bar = jQuery(this).parent().find('#foo-'+criteria+'-bar').val();

    // do stuff...

});

如何在this数组中查找包含在arr数组中的字符串,并将该字符串设为criteria变量?我在搜索这类事物时唯一能找到的就是检索数组项的索引,但这对我没有帮助。我想要实际的字符串。

提前致谢。

1 个答案:

答案 0 :(得分:1)

  1. 选择html标签的id属性值

    server.bind(10022);
    
  2. 使用jQuery按ID选择元素 - 就像使用纯JS(javascript)一样,您不需要在嵌套元素中找到元素,因为ID是每个DOM / PAGE的唯一元素

    criteria = jQuery(this).attr('id'); // just call an .attr('id');
    
  3. 您可以使用split函数从字符串中获取值:

    jQuery('#foo-'+criteria+'-bar').val();

  4. 完整示例:

    criteria = criteria.split('foo-')[1].split('-baz')[0];