简体   繁体   English

Blazor,从 Javascript 创建的 DOM 元素中获取输入值

[英]Blazor, get Input value from Javascript created DOM Element

I have been working with Blazor quite a bit ( https://blazorboilerplate.com ) but I have a bit of a issue that has stumped me tonight with adding some custom D3 code to my blazor pages. I have been working with Blazor quite a bit ( https://blazorboilerplate.com ) but I have a bit of a issue that has stumped me tonight with adding some custom D3 code to my blazor pages. The D3 / Javascript code creates several DOM input elements and I wish to retrieve the values of these created elements so I can save a DTO to my database with those values. D3 / Javascript 代码创建了几个 DOM 输入元素,我希望检索这些创建的元素的值,以便可以使用这些值将 DTO 保存到我的数据库中。 How can I do this and what is the most efficient way?我该怎么做?最有效的方法是什么? Should I just create a JSInterop method to return the input values?我应该只创建一个 JSInterop 方法来返回输入值吗?

domInput.attr("@ref", function (d3) {return d3.key});

I tried creating "@ref" attributes so I could use the ElementReference but D3 errors when I try to append an attribute that begins with '@'我尝试创建“@ref”属性,以便在尝试 append 以“@”开头的属性时使用ElementReference但出现 D3 错误

After some more research from Mr. Magoo's comment you cannot interact with DOM that was / is created by JS and / or modified by JS.在 Magoo 先生的评论中进行了更多研究后,您无法与由 JS 创建和/或由 JS 修改的 DOM 进行交互。 To get around this though you can create a JS function to return your data.要解决这个问题,您可以创建一个 JS function 来返回您的数据。 So I created a helper method that returns a JSON string of my data.所以我创建了一个帮助方法,它返回我的数据的 JSON 字符串。 Then I call that JS from my Blazor code and use Newtonsoft to Deserialize it.然后我从我的 Blazor 代码中调用该 JS 并使用 Newtonsoft 对其进行反序列化。 The d3 code could easily be changed to vanilla javascript or JQuery to get the DOM elements value / innerHTML. d3 代码可以很容易地更改为 vanilla javascript 或 JQuery 以获得 DOM 元素值/innerHTML。

Blazor Code Blazor 代码

   var data = await JsRuntime.InvokeAsync<string>("JsInteropFunc", null);

   dataDto = Newtonsoft.Json.JsonConvert.DeserializeObject<DataObjectDto> 
    (data);

Javascript Code, this case uses d3 to get the DOM Element with a class name to get the text form the DOM element: Javascript 代码,本例使用 d3 获取 DOM 元素,名称为 class 以获取 DOM 元素的文本:

  window.JsInteropFunc = function() {
    function cleanStr(data){
      return data.replace("$","").replace(",","").replace("%","");
    }

    return '{ totalSales: "' + cleanStr(d3.select(".totalSales").text()) + '"' +
            ', annualSales: "' + cleanStr(d3.select(".annualSales").text()) + '"' +
            ', profitMargin: "' + cleanStr(d3.select(".profitMargin").text()) + '"' +
            '}' ;    
  },

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

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