3

関数 A に命令コードを設定せずに、関数 B を機能させたいと考えています。実際には、長方形の上にテキストを表示します。

この質問では、ボタン A を使用して「紙」と長方形 (Raphael ライブラリを使用) を作成します。長方形の上にテキストを追加するためのボタン B。HTML コードは次のようになります。

<button onClick="func.A()">Func A</button>
<button onClick="func.B()">Func B</button>

JavaScript コードは次のようになります。

var func = (function functie($) {
    return { 
        A: function() {
            // Creates canvas 320 × 200 at 10, 50
            var paper = Raphael(10, 50, 320, 200);
            // Creates rectangle
            var bg = paper.rect(0, 0, 320, 200);
            // Sets the fill attribute of the circle to red (#f00)
            bg.attr("fill", "#f00");
            // Sets the stroke attribute of the circle to white
            bg.attr("stroke", "#fff");
        },
        B: function() {
            var t = paper.text(40, 15, "");
            t.attr('text',"new text here");
            t.attr();
        };
 })();

問題は、関数 B の命令コード (var t = paper.text(40, 15, ""); など) を関数 B に配置すると、追加しようとしたテキストが追加されないことです。長方形に。

関数 B の命令コードを関数 A に配置すると機能しますが、これは私が望むものではありません。機能Aに命令コードを設定せずに、機能Bを動作させたい。

この問題が理解できるほど明確であることを願っています。

4

1 に答える 1

2

関数 A で「var paper」を宣言すると、その変数は関数 A に対してローカルになります。関数呼び出し間で状態情報を共有する場合は、ローカル変数ではなく、オブジェクトのプロパティに状態情報を格納する必要があります。

var func = (function functie($) {
return { 
    paper: null,
    A: function() {
        // Creates canvas 320 × 200 at 10, 50
        this.paper = Raphael(10, 50, 320, 200);
        // Creates rectangle
        var bg = paper.rect(0, 0, 320, 200);
        // Sets the fill attribute of the circle to red (#f00)
        bg.attr("fill", "#f00");
        // Sets the stroke attribute of the circle to white
        bg.attr("stroke", "#fff");
    },
    B: function() {
        var t = this.paper.text(40, 15, "");
        t.attr('text',"new text here");
        t.attr();
    };
})();
于 2013-03-13T16:33:23.960 に答える