当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Find HTML elements have same data attribute values as button with jQuery

问题描述:

I'm wondering is there any way to find the HTML element on page (form, div etc) which has same data attribute value as the click button and next load that matched element into DOM.

$(document).ready(function() {

$(".btn").each(function() {

$(this).click(function() {

var btn = $(this).attr("data-value");

alert(btn);

//From Where I have to go to fetch the right matching element???

var element = $(".Form").html();

alert(element);

});

});

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />

<div class="Form" data-value="1">

<form action="#" method="post">

<h4>I'm First Element</h4>

</form>

</div>

<div class="Form" data-value="2">

<form action="#" method="post">

<h4>I'm Second Element</h4>

</form>

</div>

<button type="button" class="btn" data-value="1">Find One</button>

<button type="button" class="btn" data-value="2">Find Two</button>

网友答案:

You can select element by jquery selector.

$(this).click(function () {
                var btn = $(this).attr("data-value");
                alert(btn);
                //From Where I have to go to fetch the right matching element???
                var element = $('.Form[data-value="' + btn + '"]');
                alert(element);
            });

element is a jquery object. Now you can use this element to do your requirements.

网友答案:

Update your JavaScript Function like follow

$(document).ready(function() { 
    $(".btn").click(function() {
      var btn = $(this).attr("data-value");
      alert(btn);
      //From Where I have to go to fetch the right matching element???
      var element = $('[data-value="' + btn +'"]').html();
      alert(element);

    }); 
});
分享给朋友:
您可能感兴趣的文章:
随机阅读: