尝试使用js-cookies设置表单输入值

时间:2015-07-09 19:24:00

标签: javascript cookies

我有一个目标网页,可在您到达时在您的计算机上设置Cookie:

<input name="Web_Lead_Specific_Source__c" value="">

在另一个页面上,我有一个带有隐藏字段的表单:

Cookies.get('Web_Lead_Specific_Source__c');  => 'PPC'

如果用户访问了目标网页,我正在尝试使用“PPC”加载该值。以下代码无效:

public class MainActivity extends Activity {
    TextToSpeech myTTS;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btnSpeak = (Button)findViewById(R.id.button1);
        btnSpeak.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                speakOut();
            }
        });
        myTTS = new TextToSpeech(this, new OnInitListener() {
            public void onInit(int arg0) {}
        });


        myTTS.speak("Why doesn't this work?", TextToSpeech.QUEUE_FLUSH, null);
        speakOut();     // why doesn't this work either???
    }
    private void speakOut() {
        myTTS.speak("Why does this work?", TextToSpeech.QUEUE_FLUSH, null);
    }
    protected void onDestroy() {
        super.onDestroy();
        myTTS.shutdown();
    }
}

我确定我错过了一些东西。

1 个答案:

答案 0 :(得分:1)

只是获取 ting Cookie是不够的,您需要设置输入字段:

var leadType = Cookies.get('Web_Lead_Specific_Source__c');
var target = document.getElementsByName('Web_Lead_Specific_Source__c')[ 0 ];
target.value = leadType;

js-cookie仅负责设置和获取浏览器Cookie 的值,它不了解页面中的元素,这是不同。

这是一个具有适当面向对象命名的工作示例,以防止混淆:http://jsfiddle.net/f1fkydwh/