在jquery中选择id以字符串开头的元素

Selecting the elements whose ids start with a string in jquery

本文关键字:字符串 开头 元素 id jquery 选择      更新时间:2024-04-29

我有以下jQuery序列:

$("button").click(function(){
    if ($(this).attr('[id^=facilityName]'))
    {
        $("#facilityNameRight").text($(this).text());
    }
});

我需要if语句中的代码只有在按钮的id以"facilityName"开头并且我已经尝试了编写条件的所有组合时才能执行。怎么了?

试试这个:在绑定click事件时使用带有选择器的jquery start,而不是签入if条件。这将把click事件绑定到id以facilityName开头的按钮,并完成您所需的任务。

$("button[id^=facilityName]").click(function(){
     $("#facilityNameRight").text($(this).text());    
});

您应该将Attribute Starts With Selector[name ^="value"]与button元素一起使用。事件处理程序将附加到其idfacilityName 开头的元素

$("button[id^='facilityName']").click(function(){
     $("#facilityNameRight").text($(this).text());    
});

然而,您仍然想要if条件,您应该使用.is()

根据选择器、元素或jQuery对象检查当前匹配的元素集,如果这些元素中至少有一个与给定的参数匹配,则返回true。

  if ($(this).is('[id^=facilityName]')) {
    $("#facilityNameRight").text($(this).text());
  }

$("button").click(function() {
  if ($(this).is('[id^=facilityName]')) {
    $("#facilityNameRight").text($(this).text());
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='facilityNameTest'>facilityNameTest</button>
<button id='facilityNameTest2'>facilityNameTest2</button>
<button id='Test1'>Test1</button>
<div id="facilityNameRight"></div>

尝试:

$("button").click(function(){
    if($(this).is('[id^=facilityName]'))
    {
        $("#facilityNameRight").text($(this).text());
    }
});

可能我的答案是重复的。但我将介绍基本的调试技术,它将使您了解运行时到底发生了什么。

在您的chrome中(我主要使用chrome来调试javascript),转到源代码选项卡,在javascript文件中查看您没有得到预期结果的地方。

放置断点,看看在期望值的观察列表中得到了什么。

您只需选择完整的表达式-右键单击并选择"添加到观察列表"。

当控件处于断点时,运行时变量在该范围内是活动的。

现在,只需转到控制台,键入变量、表达式或任何您想打印的内容即可查看其值。

有关更多信息,请查看chrome开发工具