简体   繁体   中英

How to convert a prototype jquery function to javascript prototype function

I am using a crossword in jquery and for some reason i need to convert it to javascript and avoid using jquery. I have managed to convert many parts of it but i have a big problem in a prototype function and i cant understand how to convert it.

Here is the code in summary:

$("#"+cw_id).crossword();

(function($) {
// plugin definition
$.fn.crossword = function(options) {
    .....
    // implementation code goes here.    
    return this.each(function(){
      ....
    }
})();
// end plugin definition

I have tried doing this and similar to this calls but nothing is working fine.

document.getElementById("#"+cw_id).crossword();
(function() {
// plugin definition
Object.prototype.crossword = function(options) {

})();
// end plugin definition

The actual code of this prototype function is at this link: https://github.com/electricg/jQuery-Html5-Crossword/blob/master/crossword.js#L1

and the caller is at the index link: https://github.com/electricg/jQuery-Html5-Crossword/blob/master/index.html#L62

I really need to know how to convert this prototype function back to javascript Thank you in advance for any help provided

For similar functionality to jQuery, you're looking for HTMLElement.prototype .

 HTMLElement.prototype.crossword = function(text) { this.innerHTML = text; }; document.getElementById('crossword1').crossword('crossword here');
 <div id=crossword1 />

Since that's a bad idea , I would use a function and bind the element to get a similar result. You can also pass it in as an argument, but that would require more refactoring of the existing code.

 const crossword = function(text) { this.innerHTML = text; }; crossword.bind(document.getElementById('crossword1'))('crossword here');
 <div id=crossword1 />

Here you're calling function on HTML element

document.getElementById("#"+cw_id).crossword();

hence you need to define the function on it's prototype

HTMLElement.prototype.crossword = function(options) {

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM