简体   繁体   English

如果元素有类,如何包含脚本?

[英]How to include a script if element has a class?

Let's say I have:假设我有:

<body class="hello">

How can we do something like the following?我们如何做类似以下的事情?

if($("body").hasClass("hello")) {
  <script src="/demo_js/ion.rangeSlider.min.js"></script>
}

I was wondering if maybe doing something like:我想知道是否可以做类似的事情:

if($("body").hasClass("hello")) {
 document.write('<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></'+'script>');
}

That looks fine but it's a mixup of jQuery and JS and I am not sure if that's the correct way anyway.这看起来不错,但它是jQueryJS的混合体,我不确定这是否是正确的方法。

It'd be even better if this could be done via the backend in php but I am not sure how to check if an element has a class in php neither how to tell it to include a script if it does.如果这可以通过php的后端完成,那就更好了,但我不知道如何检查一个element是否在php有一个class ,也不知道如何告诉它include一个script如果有)。

How would you approach it?你会如何处理它?

One trick in php I thought is the following but then again, is there any better way?我认为php一个技巧如下,但话说回来,有没有更好的方法?

<?php
  $hello = "hello";
  if($hello) { ?>
    <script...
<?php } ?>
<body class="<?php echo $hello; ?>">

The jQuery function for this is $.getScript . jQuery 函数是$.getScript

https://api.jquery.com/jQuery.getScript/ https://api.jquery.com/jQuery.getScript/

$.getScript( "/demo_js/ion.rangeSlider.min.js" )

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

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