Answer the question
In order to leave comments, you need to log in
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
On the page:
<script>
var dataObj = {
subCat : "#<?=$subCatId?>",
mainCat : "#<?=$mainCatId?>"
}
</script>
<script src="file.js"></script>
jQuery(function() {
var $sC = jQuery(dataObj.subCat).hide();
jQuery(dataObj.mainCat).hover(
function(){
$sC.show(300);
},
function(){
$sC.hide();
}
);
});
Как вариант, с помощью 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();
}
);
});
Я бы предложил вам не заниматься подобными извращениями.
Лучше навешивайте в 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 questionAsk a Question
731 491 924 answers to any question