【问题标题】:javascript - Fill the value attribute of an input boxjavascript - 填充输入框的值属性
【发布时间】:2016-10-23 21:02:12
【问题描述】:

我正在尝试制作一个简单的 web 应用程序。 我想将主页中的数据放入另一个窗口/选项卡上的输入框,但是当我打开它时输入框总是空的。

代码如下: global.js

function showUserInfo(event) {

// Prevent Link from Firing
event.preventDefault();

var _id = $(this).attr('rel');
var arrayPosition = userListData.map(function(arrayItem) { return    arrayItem._id; }).indexOf(_id);

// Get our User Object
var thisUserObject = userListData[arrayPosition];
window.open('http://localhost:3000/editrecord', 'window', 'width=500,height=400');
var fName = thisUserObject.cName
$("#inputecName").attr('value', fname);

运行它会打开“editrecord”窗口,我试图获取的数据应该在“editrecord”页面的输入框中。

editrecord.jade

#editBox
     fieldset
          input#inputecName(type='text', placeholder='Customer Name', width = '50%')
          br
          button#btnEditRec(type='submit') Update Record

提前谢谢你。

【问题讨论】:

  • 在OP中显示相关代码
  • 你的应用是静态的还是动态的?
  • 对不起,我不小心按了回车键。 :P
  • 您在当前页面调用$("#inputecName").attr('value', fname);,虽然$#inputecName 似乎在新打开的window?还有,为什么把新开的window命名为"window"
  • $("#inputecName").attr('value', fname); 更改为$("#inputecName").val(fname); - 使用val()

标签: javascript jquery node.js pug


【解决方案1】:

js at Question 尝试将元素的value 设置为单独的document

$("#inputecName").attr('value', fname);

来自当前的document,而不是在单独的window 处引用该元素在单独的document 中。

您可以使用sessionStorage 在浏览上下文之间访问Storage 对象,或window 对象,它们具有相同的来源;在浏览器中打开editrecord.html 并加载document 时,使用.ready() 检查sessionStorage

在原html文档global.js

<script>
  sessionStorage.setItem("id", 123);
  var w = window.open("editrecord.html", "w");
</script>

editrecord.html

   <head>
    <script>
      $(document).ready(function() {
        if (sessionStorage.id) {
          $("#inputecName").val(sessionStorage.getItem("id"))
        }
      })
    </script>
  </head>

  <body>
    <input type="text" id="inputecName" />
  </body>

plnkrhttp://plnkr.co/edit/7TRQOPYPX4bMpxr6pjyX?p=preview

【讨论】:

  • 很抱歉问这个问题,'if (sessionStorage.id)' 条件是做什么的?
  • @JoseBonifacio 检查sessionStorage 是否具有id 属性,该属性将由开头window 设置。 js 的那部分可以删除;仅当设置了sessionStorage id 时,方法才会尝试设置inputvalue。例如,如果editrecords.html 由用户在原始html 文档之前打开,该文档设置sessionStorage 并使用window.open() 打开文档。 if 也可以组合成 if (sessionStorage.getItem("id") !== null)`
【解决方案2】:

你可以这样做

var childWindow = window.open('http://localhost:3000/editrecord', 'window', 'width=500,height=400');


$(childWindow.document).load(function() {

    var fName = thisUserObject.cName
    $("#inputecName").attr('value', fname);
})

您可以使用纯 javascript 从冷窗口访问 inputecName

childWindow.document.inputecName

【讨论】:

  • 我尝试放置一个随机字符串而不是 'fname',即使这样也不起作用。
【解决方案3】:

您可以通过 URL 发送数据,例如,

<a href="nextPage.html?data=blah">Next page</a>

通过JS 或服务器端脚本,您可以从URL 中获取data 并使用它,

【讨论】:

    猜你喜欢
    • 2021-01-27
    • 1970-01-01
    • 2015-02-13
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    相关资源
    最近更新 更多