简体   繁体   English

在 Javascript onClick 方法中嵌套 PHP 变量

[英]Nest PHP variable inside Javascript onClick Method

My code:我的代码:

function count_words_display($speech, $articleid){

    if (str_word_count($speech)>200){

    $speech_short = implode(' ', array_slice(explode(' ', $speech), 0, 100)).'...<input type="button" id="read" value="Read more" onclick="myFunction("'.$articleid.'","'.$speech.'")">';
    print $speech_short;
}
else{

    print $speech;
    }
}

I intend on getting output similar to this:我打算获得与此类似的输出:

<input type="button" id="read" value="Read more" onclick="myFunction('24','Play')";>

However, I end up with this:但是,我最终得到了这个:

<input type="button" id="read" value="Read more" onclick="myFunction("24","Play")";>

Resulting in this error:导致这个错误:

SyntaxError: expected expression, got '}'

尝试这个:

'...<input type="button" id="read" value="Read more" onclick="myFunction(\''.$articleid.'\',\''.$speech.'\')">';

I took your initial statements and ideas and kind of ran with it a bit.我接受了你最初的陈述和想法,并有点跑题了。

The problem you were having is that you were trying to pass a giant string to a javascript function but you couldn't really control what was going to be in the string so things got screwy.您遇到的问题是您试图将一个巨大的字符串传递给 javascript 函数,但您无法真正控制字符串中的内容,因此事情变得很棘手。

When creating the javascript onClick code, I pass a javascript variable instead of the whole string.创建 javascript onClick 代码时,我传递了一个 javascript 变量而不是整个字符串。 I set the value of that variable at the beginning of the html so it will be available when they click on it.我在 html 的开头设置了那个变量的值,这样当他们点击它时它就可用了。

Check this out:看一下这个:

<?php
//array for holding all articles 
$articles = array();

//the article in question
$article = new stdClass;
//id of the article
$article->id = 345;

//full text of the article
$article->fullText = "
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque tempus, orci a lacinia ornare, magna ante tincidunt odio, a molestie velit libero sit amet massa. Nullam volutpat diam et tellus sodales cursus. Vestibulum tempor in eros vel tristique. Vestibulum varius purus in ultrices tincidunt. Morbi mi orci, faucibus vitae tempor sed, sollicitudin ut sem. Etiam porta sem justo, et dapibus ipsum accumsan sed. Suspendisse potenti. Vestibulum id turpis mattis, rutrum dui non, varius magna. Phasellus rhoncus auctor dapibus. Ut nunc erat, sodales eget consectetur nec, interdum sit amet libero. Cras eget dui ante. Aliquam sit amet nisl vitae libero posuere hendrerit. Aliquam porta at arcu nec sodales. Pellentesque sapien nisl, facilisis eget ornare id, convallis eget erat.
Nunc cursus porttitor aliquet. Mauris sapien nibh, fermentum in turpis in, ornare malesuada nulla. Aliquam varius turpis felis, non imperdiet ante ornare eu. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla eget viverra nisl. In nunc sapien, vehicula quis tristique commodo, congue eget felis. Vestibulum vehicula velit eros. Fusce nec neque sed leo ornare mollis ut vitae urna. Suspendisse vitae nisi ut nulla egestas gravida.
Integer et pretium ligula, vitae rutrum odio. Proin condimentum lectus et odio suscipit, ut pharetra justo luctus. Integer iaculis, tortor eu sodales volutpat, nibh nisi porttitor elit, et dapibus enim odio sed augue. Praesent nec turpis non mauris tincidunt interdum non in neque. Vestibulum sagittis leo magna, in malesuada dui viverra vel. Morbi ornare urna ac est pharetra, at ornare tortor ullamcorper. Pellentesque eget libero felis. Ut scelerisque nunc at pharetra ultricies. Nullam pretium sapien ex, at viverra ligula venenatis rutrum. Proin molestie hendrerit nunc non venenatis.
";
//short form of the article
if (str_word_count($article->fullText)>200){
    $article->shortText = implode(' ', array_slice(explode(' ', $article->fullText), 0, 100)).'...<input type="button" id="read" value="Read more" onclick="myFunction(\''.$article->id.'\',fullArticle_'.$article->id.');">';
}else{
    $article->shortText = $article->fullText;
}
//javascript code that needs to be run for each article
$article->javascriptVariable = 'var fullArticle_'.$article->id.' = `'. str_replace('`',"",$article->fullText) .'`;';
//save this article in our list of articles.
array_push($articles, $article);

?>
<!DOCTYPE html>
<html>
    <head>
        <title>Testing Speech thingy</title>
        <script>
            <?php 
                //set variables in the javascript to hold the full text
                foreach ($articles as $article){
                    echo $article->javascriptVariable . "\n";
                }
            ?>;

            function myFunction(article_id, article_full) { 
                var article_body = document.getElementById(article_id); 
                article_body.innerHTML = article_full;
            }
        </script>
    </head>
    <body>
        <?php
            foreach ($articles as $article){
                echo '<div class="article-excerpt">';
                echo $article->shortText;
                echo '</div>';
                echo '<div id="'.$article->id.'">';
                echo '</div>';
            }
        ?>
    </body>
</html>

Another idea would be to just put the full text in a hidden div and then show the appropriate div when they click it.另一个想法是将全文放在隐藏的 div 中,然后在他们单击时显示适当的 div。 Doing this would avoid the need to pass any full text information via javascript function.这样做将避免需要通过 javascript 函数传递任何全文信息。 The only downside is that Google Search might lower your ranking for having duplicate content.唯一的缺点是 Google 搜索可能会降低您的排名,因为您有重复的内容。

The PHP Code PHP 代码

function count_words_display($speech, $articleid){

 if (str_word_count($speech)>200){

    $speech_short = implode(' ', array_slice(explode(' ', $speech), 0, 100)).'...<input type="button" id="read" value="Read more" onclick="myFunction('.$articleid.')">';
        print "<div id = 'short".$articleid."'>".$speech_short."</div>";

        print "<div id = 'long".$articleid."' style='display:none'>".$speech."</div>";  
 }
 else{

    print $speech;
 }
}

The JavaScript Code JavaScript 代码

function myFunction(article_id) {
 var x = document.getElementById('short'+article_id);
 var y = document.getElementById('long'+article_id);
 if (x.style.display === 'none') {
    x.style.display = 'block';
 } else {
    x.style.display = 'none';
   }

if (y.style.display === 'block') {
    y.style.display = 'none';
} else {
    y.style.display = 'block';
  }
}

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

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