开发者

'Best' way to pull data relative to a div?

开发者 https://www.devze.com 2022-12-27 15:33 出处:网络
This answer suggested i should put my data in JS instead of a textarea. Thinking about it i could have scripts and do something like myarray[i]=\"data\" where i is the index of my for loop. However w

This answer suggested i should put my data in JS instead of a textarea.

Thinking about it i could have scripts and do something like myarray[i]="data" where i is the index of my for loop. However when i click a div how do i find out what i is? I have used var data = $(this).parent('.parent').find('.valuestr').eq(0).val(); which is extremely simple. Should i use a script or should i continue to do it with a textarea? if i should use a script 1) Whats the easiest way to find i and 2) Is it bad pratice to have dozens or hundreds of <script> in my html? or i can go through the loop twice but i still dont know the easiest way to find i开发者_运维百科. I would have to store it somewhere or go through multiple tags and count them.


Answering the other part of your question:

2) Is it bad pratice to have dozens or hundreds of in my html?

It will depend on who you talk to, but in general, yes, I think it is. There's actually a push for html to be completely devoid of Javascript, save loading of .js files. For more info, look into unobtrusive javascript.

http://en.wikipedia.org/wiki/Unobtrusive_JavaScript


jQuery has a data() function just for that.

You store arbitrary data related to some element like this:

$('#my_div').data('foo', 'bar');
$('#my_div').data('hello', 'world');

Then you retrieve it like this:

alert($('#my_div').data('foo'));  // alerts "bar".
alert($('#my_div').data('hello'));  // alerts "world".


Since each DOM_Element is just an object, you can declare a variable in the object.

for(var i = 0; i < elements.length; i++)
{
   elements[i].i = i;
   elements[i].onclick = function(){
      alert(this.i);
   }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消