通过多数据属性隐藏使用jquery / javascript匹配现有变量

时间:2016-01-28 04:00:42

标签: javascript jquery dom

我正在尝试隐藏带有两个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();

2 个答案:

答案 0 :(得分:1)

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

此外,由于您要选择具有这两个属性的元素,您需要将它们组合如下

&#13;
&#13;
var bar = "New York";
var foo = "Engineer";

$('.row[data-job-type="' + foo + '"][data-job-location="' + bar + '"]').hide();
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

<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>