隐藏由多数据属性与现有变量匹配 jQuery/JavaScript

hide by multi data attributes match existing variables with jquery/javascript

本文关键字:jQuery JavaScript 变量 数据属性 隐藏      更新时间:2023-09-26

我试图隐藏一个具有两个html数据属性的div,例如下面的一个具有工程师和纽约的html数据属性

 <div class="row" data-job-type="Engineer" data-job-location="New York"></div>
 <div class="row" data-job-type="Lockmsith" data-job-location="Maryland"></div>
 <div class="row" data-job-type="Wizard" data-job-location="New York"></div>

下面我尝试以这种方式传递它,但是当我向其添加第二个属性时它不起作用。

 var bar = "New York";
 var foo = "Engineer";
 $('.row[data-job-type=' + foo + ']','.row[data-job-location=' + bar + ']').hide();

由于属性值中包含空格,因此必须将其括在"'中。

另外,由于您要选择具有两个属性的元素,因此需要按如下方式组合它们

var bar = "New York";
var foo = "Engineer";
$('.row[data-job-type="' + foo + '"][data-job-location="' + bar + '"]').hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row" data-job-type="Engineer" data-job-location="New York">1</div>
<div class="row" data-job-type="Lockmsith" data-job-location="Maryland">2</div>
<div class="row" data-job-type="Wizard" data-job-location="New York">3</div>

<html>
<head>
    <title>sample Page</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
    $(document).ready(function () {
        $('.row[data-job-type="Engineer"][data-job-location="New York"]').hide();
    });    
</script>
</head>
<body>
<div class="row" data-job-type="Engineer" data-job-location="New York">1111</div>
 <div class="row" data-job-type="Lockmsith" data-job-location="Maryland">22222</div>
 <div class="row" data-job-type="Wizard" data-job-location="New York">333333</div>
</body>
</html>