如何根据数据索引属性查找元素id

时间:2016-06-03 04:33:41

标签: javascript jquery html dom

我正在研究一个项目,我遇到了基于自定义属性(数据索引)查找元素ID的问题。 Plz有人帮助我......

HTML CODE:

<div id="2" data-index="1" style="width: 500px; left: -500px; transition-duration: 0ms; transform: translate(500px, 0px) translateZ(0px);"><b>May your birthday and every day be filled with the warmth of sunshine, the happiness of smiles, the sounds of laughter, the feeling of love and the sharing of good cheer.</b></div>

JS功能:

function saveLike(){
var currentPostion = mySwipe.getPos();
var cars = $("div").find("[data-index='" + currentPostion + "']").id;
str = JSON.stringify(cars);
console.log(str);
alert(str);

}

3 个答案:

答案 0 :(得分:0)

find选择元素的后代。您应该使用filter方法。

同样要获得id,您应该从集合中选择一个元素:

$("div").filter("[data-index='" + currentPostion + "']")[0].id;

或使用propattr方法。 jQuery集合没有id属性。

$("div").filter("[data-index='" + currentPostion + "']").prop('id');

答案 1 :(得分:0)

//我假设您正在查找该div的ID。测试

$("div[data-index='1']").attr('id')

答案 2 :(得分:0)

请检查以下工作代码获取属性值

&#13;
&#13;
function saveLike() {
  var currentPostion = 1;//mySwipe.getPos();
  var cars = $("div")[0].getAttribute('data-index');
  //find("[data-index='" + currentPostion + "']").id;
  str = JSON.stringify(cars);
  console.log(str);
  alert(str);
  return false;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="2" data-index="1" style="width: 500px; left: -500px; transition-duration: 0ms; transform: translate(500px, 0px) translateZ(0px);"><b>May your birthday and every day be filled with the warmth of sunshine, the happiness of smiles, the sounds of laughter, the feeling of love and the sharing of good cheer.</b>
</div>
<input type="button" value="save" name="save" onclick="return saveLike();">
&#13;
&#13;
&#13;