Can you set a javascript function name as an html

2020-08-25 05:39发布

问题:

Is it possible to write an html attribute that will store the name of a javascript function and then extract that val() and execute that function? Example:

<button id="example" data-function-name="showAllElements()">

and then in js/jq

fn = $('#example').data('function-name');

fn;

回答1:

You can, yes. Whether you should is another question entirely, to which the answer is almost certainly "no" (in terms of executing the string; in terms of the alternative shown below, there are times it's useful).

The way you'd evaluate that snippet of code (what you have isn't just a function name, because of the ()) would be to use the dreaded eval:

eval(fn);

There's almost always a better option than using eval. (See below.)

eval example:

$("#example").on("click", function() {
  var fn = $("#example").attr("data-function-name");
  eval(fn);
});

function showAllElements() {
  alert("showAllElements was called");
}
<button type="button" id="example" data-function-name="showAllElements()">Click Me</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


One of the better options is to store your function references as properties on an object, and then use brackets notation to get the function reference based on the function name:

Example:

var functions = {
  showAllElements: function() {
    alert("showAllElements was called");
  }
};

$("#example").on("click", function() {
  var fn = $("#example").attr("data-function-name");
  functions[fn]();
});
<button type="button" id="example" data-function-name="showAllElements">Click Me</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Note that there, I'm just storing the function name, not arbitrary code.

Update: See canon's answer for a clever way to handle it if you have your functions nested inside an object, e.g. mumble.foo.doSomething, using reduce. (reduce is an ES5 feature, but it's polyfillable.)


Side note: Unless you're doing something more than just retrieving the value of a data-* attribute, don't use data, use attr. data initializes a data cache for the element, reads in all of the data-* attributes for that element, and copies them to cache. If you're not using it, there's no reason to do that. The idea that you use data to access data-* attributes is a common misconception.



回答2:

Sure... assuming that showAllElements is global...

function showAllElements() {
  console.log("test!");
}
document.querySelector("button").addEventListener("click", function(e) {
  var functionName = this.getAttribute("data-function-name");
  window[functionName]();
});
<button id="example" data-function-name="showAllElements">x</button>

Now, let's say your attribute is actually something harrier, like: foo.bar.showAllElements...

var foo = {
  bar: {
    showAllElements: function() {
      console.log("test!");
    }
  }
};

document.querySelector("button").addEventListener("click", function(e){
    var functionName = this.getAttribute("data-function-name");
    // Split by "." and resolve each segment starting at the window. Invoke with ()
    functionName.split(".").reduce((o,n) => o[n], window)();
});
<button id="example" data-function-name="foo.bar.showAllElements">x</button>



回答3:

While I don't think you can do it this way with an HTML attribute directly (except with global functions as mentiopned above), if you can add the data element with javascript at page load you can do it directly. As said here, jquery's $.data() is not the same as the data-* attributes. According to the jQuery docs, the value stored using .data() "The new data value; this can be any Javascript type except undefined."

So you can store a function directly using

function my_func(){
   // Do stuff
}
$(function(){
   $('#foo').data('func', my_func);
});

And then later

var func = $('#foo').data('func');
if( $.isFunction( func ) ) {
   func.call( $('#foo'), somearg );
}

I have an example as a fiddle.

This has the advantage that you can have the functions in enclosures, etc. as long as you add them to the elements within the same enclosure scope.