javascript - failed to use data-name to match array although it should match -
i have
<li data-name="hello">hello</li>
i push several parameters array example var array =[]; array[0] = a:hello b:goodbye c:seeyou
so right want 1) click on li retrieve data-name value "hello" 2) check "hello" against array element "hello" 3) if match, index position , delete index array (as value "hello" in
this code used match
found = $.inarray($(this).attr("data-name"), array);
which placed in
$(".li").click(function(){ alert("data name " + $(this).attr("data-name")); found = $.inarray($(this).attr("data-name"), array); alert(found); alert("name of element " + array.a); });
as said before, when append
using above code have retrieve matching data-name "hello" , element "hello" found returns me -1 means didn't match. idea why didn't match when both alert turns out matching? thanks
your array variable contains array of objects, can't search "hello" need find object object.a == 'hello'
for can use grep (http://api.jquery.com/jquery.grep/)
$(function() { var array = [ { a: "hello", b: 'there'} , { a: "world", b: 'hi'} ]; var stuff = 'hello'; // <- can $(this).attr("data-name") var found = $.grep(array, function(n) { return n.a == stuff; }); // found list of results - want first 1 if (found.length == 1) { alert('found: ' + found[0].a); } });
fiddle: http://jsfiddle.net/yqat2/3/
update: clarification grep
takes in array , function, function must perform comparison, happen each element in input array. grep returns items comparison succeeds for. in our case return elements have a
attribute == stuff
. $(this).attr("data-name")
should go in code.
in case assumed each a
item unique, check results 1 , if so, display name found first element.
Comments
Post a Comment