I
I
Indus Indusovich2015-10-29 02:15:26
PHP
Indus Indusovich, 2015-10-29 02:15:26

How to rewrite the code, organize the function?

There is such a code jsfiddle.net/aeznsg5s
It uses the values ​​​​of variables from php, I want to put it in a separate javascript file and format it as a function, but how to do it in order to use variables from php in javascript? and how to format the function? since this code will be executed for many elements on the page, so as not to be duplicated.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vitaly Inchin ☢, 2015-10-29
@Indus999

On the page:

<script>
var dataObj = {
  subCat : "#<?=$subCatId?>",
  mainCat : "#<?=$mainCatId?>"
}
</script>
<script src="file.js"></script>

In file.js:
jQuery(function() {
  var $sC = jQuery(dataObj.subCat).hide();
  jQuery(dataObj.mainCat).hover(
     function(){
        $sC.show(300);
     },
     function(){
        $sC.hide();
     }
  );
});

E
everliving, 2015-10-29
@everliving

Как вариант, с помощью PHP создать глобальный JS объект и потом обращаться к нему из функции.

<script>
    "window.data = {'mainCatId':". $mainCatId . ",'subCatId': ". $subCatId ."}"
</script>

jQuery(function() {
      jQuery('div#'+ window.subCatId).hide();
      jQuery('div#'+ window.mainCatId ).hover(
        function(){
          jQuery(this).find('div#' + window.subCatId).show(300);
        },
        function(){
          jQuery(this).find('div#'+ window.subCatId).hide();

        }
  );
});

V
Vitaly Sivkov, 2015-10-29
@Sivkoff

Я бы предложил вам не заниматься подобными извращениями.
Лучше навешивайте в PHP классы на нужные элементы и используйте их в JS.

jQuery(function() {
    jQuery('.sub-cat').hide();
    jQuery('.main-cat').hover(
        function(){
            jQuery(this).find('.sub-cat').show(300);
        },
        function(){
            jQuery(this).find('.sub-cat').hide();
        }
    );
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question