是否可以将变量传递到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

最佳答案

您只需在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>

09-20 05:14