Acest tutorial arata cum se obtine valoarea atributului unui element cu jQuery, orice atribut adaugat in acel tag HTML (id, class, name, title, src, etc.).
- Pentru a obtine valoarea unui atribut cu jQuery, se foloseste functia attr().
Sintaxa:
$(element).click(function(){ var attrval = $(this).attr('nume_atribut'); });Acum, iata cateva coduri practice si exemple.
$('.class').click(function(){ var id = $(this).attr('id'); });
$('.class').click(function(){ var title = $(this).attr('title'); });
$('.class').click(function(){ var name = $(this).attr('name'); });
Clic pe aceasta imagine: <img src="imgs/marplo.gif" alt="marplo.net/javascript/" class="imgs" id="the_id" width="200" height="30" /> <script type="text/javascript"><!-- $(document).ready(function() { $('.imgs').click(function(){ var idimg = $(this).attr('id'); var srcimg = $(this).attr('src'); alert('ID-ul: '+ idimg+ '\n SRC: '+ srcimg); }); }); --></script>Demo:
$('#id').click(function(){ var class = $(this).attr('class'); });
$('#id').click(function(){ var name = $(this).attr('name'); });
Clic pe aceasta imagine: <img src="imgs/coursesweb.png" alt="Courses: www.coursesweb.net" class="clsimg" id="idimg" width="200" height="60" /> <script type="text/javascript"><!-- $(document).ready(function() { $('#idimg').click(function(){ var classimg = $(this).attr('class'); var altimg = $(this).attr('alt'); alert('Class: '+ classimg+ '\n Alt: '+ altimg); }); }); --></script>Demo:
$('div').click(function(){ var id = $(this).attr('id'); });
$('p').click(function(){ var class = $(this).attr('class'); });
$('input').click(function(){ var name = $(this).attr('name'); });
<div id="idiv" class="clsdiv">Clic pe acest text:<br/> Cursuri Programare Web - http://www.coursesweb.net/</div> <script type="text/javascript"><!-- $(document).ready(function() { $('div').click(function(){ var idd = $(this).attr('id'); var classdiv = $(this).attr('class'); alert('ID-ul: '+ idd+ '\n Class: '+ classdiv); }); }); --></script>Demo:
$('*').click(function(){ var id = $(this).attr('id'); });
<p>Adresa: <strong>http://CoursesWeb.net/</strong> - Tutoriale.</p>
#id { font-weight: 800; }
function someFunction() { alert("CoursesWeb.net"); } setInterval("someFunction()", 2000);
$vname = 8; echo $vname;
We have traveled in space. - Noi am calatorit (deja) in spatiu.
La niña pintaba un arco iris. - Fetita picta un curcubeu.