将变量传递给jQuery属性包含选择器

时间:2017-05-23 01:00:07

标签: javascript jquery custom-data-attribute

是否可以将变量传递给jQuery属性包含选择器?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-vp='{
  id: vp-485858383,
  customTwo: "test"
}'>
asdf
</div>

$(function() {
    var testString = "vp-485858383";
  $('[data-vp*="id: ${testString}"]').css('color', 'red');
});

我也尝试过:

$('[data-vp*="id:' +  testString + '"]').css('color', 'red');

JS Fiddle

1 个答案:

答案 0 :(得分:2)

id:

之后你只需要一个空格
$(function() {
    var testString = "vp-485858383";
  $('[data-vp*="id: ' +  testString + '"]').css('color', 'red');
});

演示

$(function() {
	var testString = "vp-485858383";
  $('[data-vp*="id: ' +  testString + '"]').css('color', 'red');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-vp='{
      id: vp-485858383,
      customTwo: "test"
}'>
asdf
</div>