![](/img/trans.png)
[英]How to call a javascript function from .js file in a Drupal module file
[英]JavaScript into Drupal Module
我正在嘗試將一個JavaScript腳本實現到Drupal 7模塊中,由於某種原因我在這里得到這個錯誤:“解析錯誤:語法錯誤,意外T_ECHO,期待')'”
我現在已經嘗試了幾個小時,但我只是不知所措。 任何幫助都會非常感激。
我的代碼塊縮進到最右邊。 其他代碼是Drupal 7中模塊的一部分供您參考。
$node->content['actions'] = array(
'#theme' => 'links',
'#prefix' => '<div id="match-actions">',
'#suffix' => '</div>',
'#links' => _match_actions($node),
echo '<script type="text/javascript">'
, 'croll();'
, 'troll();'
, '</script>';
'#attributes' => array(
'class' => array('links', 'match-actions'),
),
'#heading' => t('Match actions'),
'#weight' => -10,
);
我試圖插入的JavaScript(正如你可以看到我在上面的回聲中的嘗試)是
function class_roll() {
// Car Classes
var classes = ["B", "A", "S", "R3", "R2", "R1"],
classToUse = classes[Math.floor(Math.random() * classes.length)];
document.getElementById("croll").innerHTML = classToUse ;
}
function track_roll() {
var tracks = ["Clear Springs Circuit", "Festival North Circuit", "Beaumont Circuit", "Finley Dam Circuit", "Gladstone Circuit", "Clifton Valley Trail", "Gladstone Trail", "Red Rock Descent", "Red Rock Hill Climb"],
trackToUse = tracks[Math.floor(Math.random() * tracks.length)];
document.getElementById("troll").innerHTML = trackToUse ;
}
我究竟做錯了什么? 我一直在尋找Stack和網絡,這使我能夠嘗試不同的語法,但我無法讓它工作。 我不是JS和PHP的專家,但我正在努力學習:)。 再次,任何幫助真的很感激。
PS - 在HTML術語中,我想要做的是:
<p id="croll">Some text here</p>
<p id="troll">Some text here</p>
<button onclick="class_roll(); track_roll();">Class Roll</button>
但是如果不是做一個onclick類型的PHP動作,它將是一個onload類型的事件,但它只會第一次上載並堅持並保持靜態,這將是很好的。
您不能在數組中放置回聲。
你應該能夠做到:
$links = _match_actions($node);
$links[] = '<script type="text/javascript"> croll(); troll(); </script>'
$node->content['actions'] = array(
'#theme' => 'links',
'#prefix' => '<div id="match-actions">',
'#suffix' => '</div>',
'#links' => $links,
'#attributes' => array(
'class' => array('links', 'match-actions'),
),
'#heading' => t('Match actions'),
'#weight' => -10,
);
正如HorusKol所說,你無法直接調用模塊中的JavaScript函數。 模塊的原因是用PHP編寫的,並且不能將其他編程語言的函數調用為一個。
如果要插入JavaScript代碼,則應使用drupal_add_js ()函數來執行此操作。
因此,您可以使用以下內容替換echo
:
echo drupal_add_js('croll();troll();','inline');
更好的方法,不會像Drupal AJAX那樣破壞,就是使用Drupal行為。
(function ($) {
Drupal.behaviors.myModuleName = {
attach : function (context, settings) {
$(".match-actions", context).once('match-actions', function(){
croll();
troll();
})
}
}
})(jQuery);
將其放在js文件中並使用drupal_add_js加載它(drupal_get_path('module','{my module name}')。'{js file name}');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.