jQuery-在第三方表单上预填充表单字段 [英] JQuery - prepopulate form field on 3rd party form

查看:39
本文介绍了jQuery-在第三方表单上预填充表单字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网页上有一个Netresults表单,需要预先填充.表单已使用javascript插入页面中,因此我无法在源代码中看到表单字段.

I have a Netresults form on my webpage that I need to prepopulate. The form is inserted into the page with javascript and so I am unable to see the form fields in the source code.

如果表单在我的页面上,我将使用以下代码,但实际上,我不知道如何定位字段.有人可以帮忙吗?

I would use the below code if the form was on my page but as its not, I have no idea how to target the fields. Can anyone help?

var keywords = getUrlParameter('keywords');

$('input[name=netres-keywords]').val(keywords);

使用以下代码插入netresults表单:

The netresults form is inserted with this code:

(function() {
    var $__MAForm;
    ($__MAForm =function(){
        if(typeof($__MA)=="undefined"){
            return window.setTimeout($__MAForm,50);
        }else{
            $__MA.addMAForm("43788303-2b62-4774-ad0f-63542e3ed92a", "forms.example.com");
        }
    })();
})();

推荐答案

这可能需要使用突变观察者将检查DOM(添加的元素等)是否发生更改,我们可以使用它来触发事件.每当将新的< form> 元素添加到< body> .

A mutation observer will check for changes to the DOM (added elements, etc), and we can use this to fire an event. The code below will change the value of an input with name netres-keywords any time a new <form> element is added to the <body>.

在本文底部的示例JSFiddle中,我创建了一个按钮,用于模拟要添加到页面的表单.如您所见,文本框将预先填充.

In the example JSFiddle at the bottom of this post, I've created a button that simulates a form being added to the page. As you can see, the textbox will pre-populate.

示例JSFIDDLE

$(document).ready(function() {

    var keywords = "this is a test keyword";
    var formCount = $("form").length;

    var observer = new MutationObserver(function() {
        var newFormCount = $("form").length;
        if (newFormCount > formCount) {
            $('input[name=netres-keywords]').last().val(keywords);
        }
    });

    $("button").click(function() {
        $form = $("<form>").html("<h1>New form:</h1><input type='text' name='netres-keywords'>");
        $("body").append($form);
    });
    
    var observerConfig = {
        attributes: true, 
        childList: true, 
        characterData: true 
    };
    
    var targetNode = document.body;
    observer.observe(targetNode, observerConfig);
});

form {
    padding: 10px;
    border: 1px solid red;
    margin-bottom: 20px;
}

h1 {
    margin: 0;
    padding: 0;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>
    SIMULATE ADDING FORM
</button>
<br>
<br>

这篇关于jQuery-在第三方表单上预填充表单字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆