简体   繁体   English

在JavaScript中运行php函数的语法

[英]Syntax to run a php Function inside javascript

I have tried different approaches to get this to work. 我尝试了不同的方法来使它起作用。 I know I have to wrap the function but can not get it to work. 我知道我必须包装该功能,但无法使其正常工作。 The function is running in a .js file. 该函数在.js文件中运行。

http://jsfiddle.net/hookedonweb/yq8Hz/ http://jsfiddle.net/hookedonweb/yq8Hz/

function showLabel(labelName) {
   var labelImgs = jQuery(".content .packaging .labels img");
   var focusImg  = jQuery("#label_" + labelName);

   if (labelImgs.length > 0 && focusImg.length > 0) {
       labelImgs.each(function() { jQuery(this).removeClass("active"); });

       focusImg.addClass("active");
   }
}

I think you may be confusing PHP and jQuery. 我认为您可能会混淆PHP和jQuery。 Anyways, your code can be simplified a lot. 无论如何,您的代码可以简化很多。 This seems to do what you want. 这似乎可以满足您的要求。 If it doesn't then you need to clarify your question. 如果不是,那么您需要澄清您的问题。

http://jsfiddle.net/yq8Hz/3/ http://jsfiddle.net/yq8Hz/3/

Don't use inline javascript. 不要使用内联JavaScript。 You are using jQuery, so use it to separate your code from your html. 您正在使用jQuery,因此请使用它来将您的代码与html分开。 This is a good practice. 这是一个好习惯。 You can use the data attributes to store the img you want to reference. 您可以使用数据属性存储要引用的img。

<div><a href="" data-label="macandcheese">See Label</a></div>
<div><a href="" data-label="lasagna">See Label</a></div>
<div><a href="" data-label="beefstroganoff">See Label</a></div>

Then use jQuery's hover to add/remove the active class. 然后使用jQuery的鼠标悬停来添加/删除活动类。 We make use of jQuery's data method to get the label we want. 我们利用jQuery的data方法来获取所需的标签。

$('a').hover( function() {
    $('img').removeClass('active');
    $('img#label_' +  $(this).data('label')).addClass('active');
});​

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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