Unobtrusive JavaScript - Safe Attributes?

I am working on splitting JavaScript code from my HTML. I currently have some code that looks like this:

<div onclick="return do_something_with('100566');" class="clickable">Click Me!</div>

      

I would like to change the onclick to an attribute containing only the parameter that I pass to the method.

I am using jQuery for this with the following type of code:

var $j = jQuery;
$j(function(){
    $j('.clickable').live('click',function(){
        param = $j(this).attr('attribute_name');
        do_something(param);
    });
});

      

What attribute can I use for 'attribute_name' that would be safe to pass this parameter value? I know I can use id, but I would already be defining an element with the same id elsewhere in the DOM.

Any suggestions?

+2


source to share


6 answers


Why don't you make these tags a

? There are several sites that use the anchor ( #someThing

) part or use an attribute rel

.



0


source


I usually add a meaningful prefix, for example Client-100566

, and then refer to it with this code:

var param = $(this).attr("id").split("-")[1];

      



Edit: Eliminated suggestion about invalid all-number id toker.

+4


source


I often find myself either using help id

for things to be unique or hiding hidden <span>

with data.

+2


source


Can't use rel tag on a

inside div

? It allows you to pass 1 parameter or n parameters for doSomething.

<div>
  <a class="clickable" rel="param1 param2 param3">Click Me!</a>
</div>

      

So now, when param is sent to doSomething, is it a space separated list that param.indexOf("param1")

can be used to check what parameters were sent via?

+1


source


You can use class or header attributes as parameter lists, separated by spaces. The downside to the title is that it will show up as a popup when your element is hovering:

<div class="clickable param1 param2 param3">

      

or

<div class="clickable" title="param1 param2 param3">

      

Here is a list of other attributes .

0


source


You can just create any attribute name you like.

<div onclick="foo();" silkyvalue="12938">hello</div>

      

I would generally go with some naming format though "my_somethingID" for example.

0


source







All Articles